你需要在所有 bash 脚本中使用 shebang 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7615430/
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
Do you need shebang in all bash scripts?
提问by Raihan
Suppose you have a bash script B, that you are sourcing from another bash script A. B has a bunch of variable and function definitions. A is the main driver script. Do you need the #!/bin/bash line on top of both A and B? What happens if you do and if you don't?
假设你有一个 bash 脚本 B,你是从另一个 bash 脚本 A 获取的。 B 有一堆变量和函数定义。A 是主要的驱动程序脚本。您是否需要在 A 和 B 顶部使用 #!/bin/bash 行?如果你这样做,如果你不这样做,会发生什么?
回答by A.H.
The shebang is only mandatory for those scripts, which shall be executed by the operating system in the same way as binary executables. If you source in another script, then the shebang is ignored.
shebang 仅对那些脚本是强制性的,它们应由操作系统以与二进制可执行文件相同的方式执行。如果您在另一个脚本中获取源代码,则将忽略 shebang。
On the other hand. IF a script is supposed to be sourced, then it is convention to NOT put any shebang at the start.
另一方面。如果脚本应该是源代码,那么惯例是不要在开始时放置任何shebang。
回答by Mark Byers
The shebang is used if you run the script directly as an executable file (for example with the command ./script.sh). In this case it tells the operating system which executable to run.
如果您直接将脚本作为可执行文件运行(例如使用命令./script.sh),则会使用 shebang 。在这种情况下,它告诉操作系统要运行哪个可执行文件。
It's not required and has no effect if you for example write bash ./script.shor source the script.
例如,如果您编写bash ./script.sh或获取脚本,则它不是必需的,并且不会产生任何影响。
回答by Micha? ?rajer
You should use shebang in all scripts especially those using any non-sh compatible features.
您应该在所有脚本中使用 shebang,尤其是那些使用任何非 sh 兼容功能的脚本。
In Debian for example, default shell is dash (not bash). If you use bash-only feature and don't specify that this script should be interpreted by bash it may fail even on linux. It will fail on Solaris or HP-UX almost for sure.
例如,在 Debian 中,默认 shell 是 dash(不是 bash)。如果您使用 bash-only 功能并且未指定该脚本应由 bash 解释,则即使在 linux 上也可能会失败。它几乎肯定会在 Solaris 或 HP-UX 上失败。
If your file is to be only sources by other script, then you can omit shebang line but do not set executable permission. Also for such files is good to keep /bin/sh compatibility.
如果您的文件只是其他脚本的源,那么您可以省略 shebang 行但不要设置可执行权限。对于这样的文件,保持 /bin/sh 兼容性也很好。
I strongly recommend to read DashAsBinSh.
我强烈建议阅读DashAsBinSh。

