当写 Shell Script 时, 很多时需要取得 Shell Script 本身的目录位置, 以下教学是在 Shell Script 取得目录位置的写法。
在 Shell Script 的 $0 变量代表指令的第一个参数, 即 Shell Script 本身, 例如 Shell Script 是 “/root/test.sh”:
#!/usr/bin/sh
echo $0
执行时会返回:
# /root/test.sh
/root/test.sh
/root/test.sh
所以最简单的方法是用 dirname, 将 /home/samtang/test.sh 的目录位置取得, 例如:
|
1 2 3 4 |
#!/usr/bin/sh BASEDIR=$(dirname "$0") echo "$BASEDIR" |
执行结果会返回:
# /root/test.sh
/root
/root
以上写法虽然简单, 但如果用相对路径执行, 只会返回相对路径的目录, 例如:
# cd /root
# ./test.sh
.
# ./test.sh
.
可以看到上面的例子只会返回 “.”, 当然如果执行的 Shell Script 全部用完整的绝对路径便不用理会, 但如果想要不论用绝对路径或相对路径都可以显示正确, 可以用以下程式码:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#!/usr/bin/sh get_script_dir () { SOURCE="${BASH_SOURCE[0]}" # While $SOURCE is a symlink, resolve it while [ -h "$SOURCE" ]; do DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" SOURCE="$( readlink "$SOURCE" )" # If $SOURCE was a relative symlink (so no "/" as prefix, need to resolve it relative to the symlink base directory [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" done DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" echo "$DIR" } echo "$(get_script_dir)" |
以上 Shell Script 可以正确显示绝对路径或相对路径的目录。