Linux 使用 sh 运行 bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19538669/
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
Run bash script with sh
提问by Lemon Tree
I have bash script and it requires bash.
我有 bash 脚本,它需要 bash。
Another person try to run it with
另一个人尝试运行它
sh script_name.sh
And it fails because sh is symbolic link to dash in his distribution.
它失败了,因为 sh 是他的发行版中 dash 的符号链接。
$ ls -la /bin/sh
lrwxrwxrwx 1 root root 4 Aug 25 16:06 /bin/sh -> dash
I have an idea to use wrapper script:
我有一个使用包装脚本的想法:
#!/bin/sh
bash script_name.sh
The goal is to run .sh script by sh with bash in system having symbolic link to dash.
目标是在系统中通过 sh 使用 bash 运行 .sh 脚本,该系统具有到 dash 的符号链接。
采纳答案by neuro
Well, usually you use the shebangto tell the shell to use the correct interpreter:
好吧,通常你使用shebang告诉shell使用正确的解释器:
#!/bin/bash
# your script here
You have to set the script to be executable:
您必须将脚本设置为可执行:
chmod +x my_script.sh
And let the user start it with:
并让用户启动它:
./my_script.sh
It seems simple than to use a wrapper script.
这似乎比使用包装脚本简单。
You can use jbr test to run your script with bash even if the user use sh/dash or any sh like interpreter:
即使用户使用 sh/dash 或任何类似解释器的 sh,您也可以使用 jbr test 用 bash 运行您的脚本:
#!/bin/bash
if [ -z "$BASH_VERSION" ]
then
exec bash "sh ./my_script.sh
# or
bash ./my_script.sh
# or
./my_script.sh
" "$@"
fi
# Your script here
This way it correctly works with either :
这样它就可以正确地与以下任一者一起使用:
if [ "$BASH" != "/bin/bash" ]; then
echo "Please do ./if [ -z "$BASH_VERSION" ]; then
echo "Please do ./##代码##"
exit 1
fi
"
exit 1
fi
回答by jbr
In your script before you anything else, you can do something like:
在您执行其他任何操作之前的脚本中,您可以执行以下操作:
##代码##or the more general way is using $BASH_VERSION
:
或者更通用的方法是使用$BASH_VERSION
: