有没有办法强制 shell 脚本在 bash 而不是 sh 下运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17752204/
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
Is there a way to force a shell script to run under bash instead of sh?
提问by Locane
I've been goggling around trying to find this, but I couldn't find anything off hand. I'm sure the answer is straightforward.
我一直在四处寻找这个,但我找不到任何手头的东西。我相信答案很简单。
I'm writing some shell scripts for various purposes to be run by different people, and some of them may invoke the script with "sh" instead of "bash".
我正在编写一些用于各种目的的 shell 脚本,以便由不同的人运行,其中一些人可能会使用“sh”而不是“bash”来调用脚本。
The script contains tools that do not operate in the regular shell environment and need bash - is there a way to force the script to be run under bash even though it was invoked with "sh"?
该脚本包含不在常规 shell 环境中运行并且需要 bash 的工具 - 有没有办法强制脚本在 bash 下运行,即使它是用“sh”调用的?
回答by Keith Thompson
As Richard Pennington says, the right way to do that is to have
正如理查德彭宁顿所说,做到这一点的正确方法是让
#!/bin/bash
as the first line of the script.
作为脚本的第一行。
But that's not going to help if users invoke it using shexplicitly. For example, if I type
但是,如果用户使用sh显式调用它,那将无济于事。例如,如果我输入
sh your-script-name
the #!line will be ignored.
该#!行将被忽略。
You can't really preventpeople from doing that, but you can discourage it by adding something like this at the top of the script:
你不能真正阻止人们这样做,但你可以通过在脚本顶部添加这样的东西来阻止它:
#!/bin/bash
if [ ! "$BASH_VERSION" ] ; then
echo "Please do not use sh to run this script (#!/bin/bash
if [ ! "$BASH_VERSION" ] ; then
exec /bin/bash "#! /bin/bash
# The rest of your script.
" "$@"
fi
), just execute it directly" 1>&2
exit 1
fi
Or you could do something like:
或者你可以这样做:
##代码##but that could go very wrong very easily; for example, it's probably not guaranteed that $0, which is normally the name of the script, is actually a name you can use to invoke it. I can imagine this going into an infinite loop if you get it wrong or if your system is slightly misconfigured.
但这很容易出错;例如,可能无法保证 ,$0通常是脚本的名称,实际上是您可以用来调用它的名称。我可以想象如果你弄错了或者你的系统配置有点错误,这会进入一个无限循环。
I recommend the error message approach.
我推荐错误消息方法。
(Note: I've just edited this answer so the error message includes the name of the script, which could be helpful to users.)
(注意:我刚刚编辑了这个答案,因此错误消息包含脚本的名称,这可能对用户有所帮助。)

