Determine the path of the executing BASH script
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Can a Bash script tell what directory it's stored in?
在Windows命令脚本中,可以使用
1 | @echo Running from %~dp0 |
bash脚本中的等价物是什么?
对于相对路径(即直接等效于windows'EDOCX1[0]):
1 2 | MY_PATH="`dirname "$0"`" echo"$MY_PATH" |
对于绝对标准化路径:
1 2 3 4 5 6 7 8 | MY_PATH="`dirname "$0"`" # relative MY_PATH="`( cd "$MY_PATH" && pwd )`" # absolutized and normalized if [ -z"$MY_PATH" ] ; then # error; for some reason, the path is not accessible # to the script (e.g. permissions re-evaled after suid) exit 1 # fail fi echo"$MY_PATH" |
假设键入bash脚本的完整路径,则使用
1 2 3 | #!/bin/bash echo"$0" dirname"$0" |
实例输出:
1 2 3 | $ /a/b/c/myScript.bash /a/b/c/myScript.bash /a/b/c |
如有必要,将
编辑:添加引号以处理空格字符。
Stephane Chazelas在C.U.S.假设posix shell:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | prg=$0 if [ ! -e"$prg" ]; then case $prg in (*/*) exit 1;; (*) prg=$(command -v --"$prg") || exit;; esac fi dir=$( cd -P --"$(dirname --"$prg")" && pwd -P ) || exit prg=$dir/$(basename --"$prg") || exit printf '%s '"$prg" |
1 | echo Running from `dirname $0` |
VLAD的代码报价过高。应该是:
1 2 | MY_PATH=`dirname"$0"` MY_PATH=`( cd"$MY_PATH" && pwd )` |