为什么shell脚本这么难开发?在 NodeJS 中,我可以简单地做:
require('./script')
Run Code Online (Sandbox Code Playgroud)
并且它总是需要script
相对于当前脚本。但是如果我在 shell/bash 中尝试:
./script.sh
Run Code Online (Sandbox Code Playgroud)
它将寻找相对于cwd
( pwd
) 的脚本。似乎点表示cwd
( pwd
) 而不是我预期的当前脚本所在的目录。
line 8: ./script.sh: No such file or directory
Run Code Online (Sandbox Code Playgroud)
如何执行相对于当前执行脚本所在目录的脚本?
我试过了
/bin/bash script.sh
Run Code Online (Sandbox Code Playgroud)
但我收到错误:
/bin/bash: script.sh: No such file or directory
Run Code Online (Sandbox Code Playgroud)
然后我试过了
script.sh
Run Code Online (Sandbox Code Playgroud)
得到这个错误
line 8: script.sh: command not found
Run Code Online (Sandbox Code Playgroud)
只有以下解决方案工作正常,但问题是它不可读:
$("$(dirname "$(realpath "$0")")/script.sh")
Run Code Online (Sandbox Code Playgroud)
dan*_*bst 14
获取脚本目录的另一个变体:
DIR="$(cd "$(dirname "$0")" && pwd)"
Run Code Online (Sandbox Code Playgroud)
然后你可以调用脚本
$DIR/script.sh
Run Code Online (Sandbox Code Playgroud)
不幸的是,这是要走的路。
另一种方法(我更喜欢)是在脚本的开头 cd 到当前目录,如下所示:
cd $(dirname $0)
Run Code Online (Sandbox Code Playgroud)
正如其他答案所示,您的解决方案是正确的。
\n正如其他答案所建议的,\n您可以获取脚本目录一次并多次使用它。\xc2\xa0\n这个\xc2\xa0可能更干净、更高效。
\n正如其他答案所建议的,您可能不需要 \xc2\xa0realpath
。\xc2\xa0\n你能说出为什么你相信 \xc2\xa0 你需要 \xc2\xa0it 吗?
你似乎有一个额外$(
的)
。
"$(dirname "$(realpath "$0")")/script.sh"\n
Run Code Online (Sandbox Code Playgroud)\n应该足够\xe2\x80\xa6
\n\xe2\x80\xa6 除外,\xe2\x80\x99s 是一个非常微妙的极端情况,没有其他人指出。\xc2\xa0\n让 \xe2\x80\x99s 均匀化其他答案:
\nDIR="$(dirname "$(realpath "$0")")"\n"$DIR"/script.sh\n
Run Code Online (Sandbox Code Playgroud)\n如果\xe2\x80\x9c当前脚本\xe2\x80\x9d位于根目录\n(例如,它是/first_script
),\n并且假设realpath
\xe2\x80\x99t没有任何\xc2\xa0效果,\n我们\ xc2\xa0 将得到\xc2\xa0 DIR="/"
,所以
"$DIR"/script.sh\n
Run Code Online (Sandbox Code Playgroud)\n线将扩展为
\n"/"/script.sh\n
Run Code Online (Sandbox Code Playgroud)\nIE,
\n//script.sh\n
Run Code Online (Sandbox Code Playgroud)\n这通常相当于.\xc2\xa0\n但是 Unix (POSIX) 保留在 \xc2\xa0 路径名开头特殊处理\n/script.sh
的权利。\xc2\xa0\n这样做要安全得多//
DIR="$(dirname "$(realpath "$0")")"/\n"$DIR"/script.sh\n
Run Code Online (Sandbox Code Playgroud)\n在 .\xc2\xa0\n如果\xc2\xa0是\xc2\xa0/
的定义末尾带有(额外的、显式的),将被设置为\xc2\xa0 ,\n并将扩展为\xc2\xa0 ,\n这保证等于.\xc2\xa0\n并且\xc2\xa0if\xc2\xa0是更常见的东西,例如,\n那么将被设置为\xc2\xa0 ,\n并且将被扩展为\xc2 \xa0 ,\n这也保证等于.DIR
$0
/first_script
DIR
//
"$DIR"/script.sh
///script.sh
/script.sh
$0
/foo/bin/first_script
DIR
/foo/bin/
"$DIR"/script.sh
/foo/bin//script.sh
/foo/bin/script.sh