Reputation: 1463
I have written a test script( let's call it test.sh) in bash. and the start of the script has following declaration:
#!/bin/bash -e
followed by some code.
Now it shows different results when i invoke it as bash test.sh
versus ./test.sh
. How is it possible. I thought by default ./test.sh
reads the default shell from the first line of script and invokes it with that. Is my understanding correct.
Upvotes: 1
Views: 246
Reputation: 12003
The #!/bin/bash -e
shebang is only used when you (try to) execute a file (that isn’t a binary executable) as a command. This line informs the kernel which executable should be used to interpret the code in the script. See the shebang Wikipedia article for more information.
When you run ./test.sh
, your current shell starts a new Bash sub-process with the -e
option and this new process is the one that executes the commands in the script file.
When you run bash test.sh
, you’re explicitly starting a new Bash sub-process (this time without the -e
option) and it starts executing the commands in the file. When it encounters the shebang in the first line, it just treats it the same as any other comment beginning with #
. (The shebang is also ignored as just another comment if you source
the file using . test.sh
).
To ensure that the Bash shell behaves a certain way, it’s best to use the set
builtin instead of providing an option when invoking Bash. E.g., to ensure the shell exits when a command returns a non-zero status, you should include set -e
at or near the start of the script.
For more in-depth information about how commands are executed with a Linux kernel, see this answer to What is the difference between running “bash script.sh” and “./script.sh” and the execve
man page.
Upvotes: 2