Bash Shebang for dummies?
I have some bash scripts I have setup that mostly use
#!/bin/bash
but I regularly come across some that look like
#!/bin/bash -e
#!/bin/bash -x
#!/bin/bash -ex
and so on.
Can someone explain the meaning and benefits of these shebang options and whether they apply to other shebangs?
Solution 1:
If a script /path/to/foo
begins with #!/bin/bash
, then executing /path/to/foo arg1 arg2
is equivalent to executing /bin/bash /path/too/foo arg1 arg2
. If the shebang line is #!/bin/bash -ex
, it is equivalent to executing /bin/bash -ex /path/too/foo arg1 arg2
. This feature is managed by the kernel.
Note that you can portably have only one argument on the shebang line: some unices (such as Linux) only accept one argument, so that #!/bin/bash -e -x
would lead to bash receiving the single five-character argument -e -x
(a syntax error) rather than two arguments -e
and -x
.
For the Bourne shell sh
and derived shells such as POSIX sh, bash, ksh, and zsh:
-
-e
means that if any command fails (which it indicates by returning a nonzero status), the script will terminate immediately. -
-x
causes the shell to print an execution trace.
Other programs may understand these options but with different meanings.
Solution 2:
They are options passed to bash
see help set
for more info, in this case:
-x Print commands and their arguments as they are executed.
-e Exit immediately if a command exits with a non-zero status.