确定执行 BASH 脚本的路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/630372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Determine the path of the executing BASH script
提问by Atif Aziz
Possible Duplicate:
Can a Bash script tell what directory it's stored in?
可能的重复:
Bash 脚本可以告诉它存储在哪个目录中吗?
In a Windows command script, one can determine the directorypath of the currently executing script using %~dp0
. For example:
在Windows命令脚本,就可以确定目录使用当前执行脚本的路径%~dp0
。例如:
@echo Running from %~dp0
What would be the equivalent in a BASHscript?
BASH脚本中的等价物是什么?
回答by vladr
For the relative path (i.e. the direct equivalent of Windows' %~dp0
):
对于相对路径(即 Windows' 的直接等效项%~dp0
):
MY_PATH="`dirname \"MY_PATH="`dirname \"#!/bin/bash
echo "$ /a/b/c/myScript.bash
/a/b/c/myScript.bash
/a/b/c
"
dirname "prg=echo Running from `dirname MY_PATH=`dirname "##代码##"`
MY_PATH=`( cd "$MY_PATH" && pwd )`
`
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\n' "$prg"
"
\"`" # 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"
\"`"
echo "$MY_PATH"
For the absolute, normalized path:
对于绝对的标准化路径:
##代码##回答by Alex Reynolds
Assuming you type in the full path to the bash script, use $0
and dirname
, e.g.:
假设您输入 bash 脚本的完整路径,请使用$0
和dirname
,例如:
Example output:
示例输出:
##代码##If necessary, append the results of the $PWD
variable to a relative path.
如有必要,将$PWD
变量的结果附加到相对路径。
EDIT: Added quotation marks to handle space characters.
编辑:添加引号来处理空格字符。
回答by Dimitre Radoulov
Contributed by Stephane CHAZELASon c.u.s. Assuming POSIX shell:
由Stephane CHAZELAS在cusAssuming POSIX shell 上贡献:
##代码##回答by xagyg
回答by Poor Yorick
Vlad's code is overquoted. Should be:
弗拉德的代码被高估了。应该:
##代码##