我如何找到一个Bash脚本位于该脚本内部的目录的路径?
我想用Bash脚本作为另一个应用程序的启动器,我想将工作目录更改为Bash脚本所在的目录,所以我可以在该目录中的文件上运行,如下:
$ ./application
我如何找到一个Bash脚本位于该脚本内部的目录的路径?
我想用Bash脚本作为另一个应用程序的启动器,我想将工作目录更改为Bash脚本所在的目录,所以我可以在该目录中的文件上运行,如下:
$ ./application
当前回答
尝试一下这样的东西:
function get_realpath() {
if [[ -f "$1" ]]
then
# The file *must* exist
if cd "$(echo "${1%/*}")" &>/dev/null
then
# The file *may* not be local.
# The exception is ./file.ext
# tTry 'cd .; cd -;' *works!*
local tmppwd="$PWD"
cd - &>/dev/null
else
# file *must* be local
local tmppwd="$PWD"
fi
else
# The file *cannot* exist
return 1 # Failure
fi
# Reassemble realpath
echo "$tmppwd"/"${1##*/}"
return 0 # Success
}
function get_dirname(){
local realpath="$(get_realpath "$1")"
if (( $? )) # True when non-zero.
then
return $? # Failure
fi
echo "${realpath%/*}"
return 0 # Success
}
# Then from the top level:
get_dirname './script.sh'
# Or within a script:
get_dirname "$0"
# Can even test the outcome!
if (( $? )) # True when non-zero.
then
exit 1 # Failure
fi
這些功能和相關工具是我們的產品的一部分,已為社區提供免費,可以在GitHub找到作為 realpath-lib. 它是簡單的,清潔和良好的文档(很棒的學習),純粹的Bash,並沒有依賴。
source '/path/to/realpath-lib'
get_dirname "$0"
if (( $? )) # True when non-zero.
then
exit 1 # Failure
fi
其他回答
这里是JavaScript(即Node.js)的替代方案:
baseDirRelative=$(dirname "$0")
baseDir=$(node -e "console.log(require('path').resolve('$baseDirRelative'))") # Get absolute path using Node.js
echo $baseDir
在我看来,最合适的解决方案是:
"$( cd "$( echo "${BASH_SOURCE[0]%/*}" )"; pwd )"
使用 dirname、 readlink 和 basename 最终会导致兼容性问题,所以如果可能的话最好避免。
没有<unk>(除了<unk>)和可以处理“陌生人”名称的形式,如那些有新闻,因为有些人会声称:
IFS= read -rd '' DIR < <([[ $BASH_SOURCE != */* ]] || cd "${BASH_SOURCE%/*}/" >&- && echo -n "$PWD")
如果不是由父母脚本来源,而不是同链接,0美元就足够了:
script_path="$0"
如果源于父母脚本而不是同链接,请使用 $BASH_SOURCE 或 ${BASH_SOURCE[0]}:
script_path="$BASH_SOURCE"
如果是同链接,请使用 $BASH_SOURCE 与 realpath 或 readlink -f 获取真正的文件路径:
script_path="$(realpath "$BASH_SOURCE")"
此外,路径或 readlink -f 返回绝对路径。
要获取脚本的目录,使用 dirname:
script_directory="$(dirname "$script_path")"
笔记
对于 MacOS 而言,请在这里或在这里找到一个替代路径或阅读链接 -f. 要使代码与不为 Bash 的支柱兼容,请使用 ${var-string} 参数扩展。
尝试使用:
real=$(realpath "$(dirname "$0")")