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.
精彩评论