开发者

Do you need shebang in all bash scripts? [duplicate]

开发者 https://www.devze.com 2023-04-10 00:20 出处:网络
This question already has answers here:开发者_如何学运维 Should I use a Shebang with Bash scripts?
This question already has answers here: 开发者_如何学运维 Should I use a Shebang with Bash scripts? (8 answers) Closed 8 years ago.

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?


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.

On the other hand. IF a script is supposed to be sourced, then it is convention to NOT put any shebang at the start.


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.

It's not required and has no effect if you for example write bash ./script.sh or source the script.


You should use shebang in all scripts especially those using any non-sh compatible features.

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.

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.

I strongly recommend to read DashAsBinSh.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号