linux - bash script invocation shows inconsistent behavior -
i have written test script( let's call test.sh) in bash. , start of script has following declaration:
#!/bin/bash -e
followed code.
now shows different results when invoke bash test.sh
versus ./test.sh
. how possible. thought default ./test.sh
reads default shell first line of script , invokes that. understanding correct.
the #!/bin/bash -e
shebang used when (try to) execute file (that isn’t binary executable) command. line informs kernel executable should used interpret code in script. see shebang wikipedia article more information.
when run ./test.sh
, current shell starts new bash sub-process -e
option , new process 1 executes commands in script file.
when run bash test.sh
, you’re explicitly starting new bash sub-process (this time without -e
option) , starts executing commands in file. when encounters shebang in first line, treats same other comment beginning #
. (the shebang ignored comment if source
file using . test.sh
).
to ensure bash shell behaves way, it’s best use set
builtin instead of providing option when invoking bash. e.g., ensure shell exits when command returns non-zero status, should include set -e
@ or near start of script.
for more in-depth information how commands executed linux kernel, see this answer what difference between running “bash script.sh” , “./script.sh” , execve
man page.
Comments
Post a Comment