获取当前shell脚本的绝对路径
#! /bin/bash # 获取当前shell脚本的绝对路径 path=$(cd `dirname $0`;pwd) echo $path
具体含义如下:
dirname $0:取得当前执行的脚本文件的父目录
cd `dirname $0`:进入这个目录(切换当前工作目录)
pwd:显示当前工作目录(cd执行后的)
遇到的问题:sudo后 环境变量被重置为默认
解决办法:在/etc/sudoers中修改,把 Defaults env_reset 修改为 Defaults !env_reset 。这样,任何环境变量都可以通过sudo传进去了。
引用变量时添加双引号,可以保留输出的空格和换行符( )
#! /bin/bash # file的内容:1 2 3 out=`cat file` # 丢失了部分空格(多个空格变成了一个空格) echo $out # 输出:1 2 3 # 引用变量时添加双引号,可以保留输出的空格和换行符( ) echo "$out" # 输出:1 2 3