The main way I know to debug scripts is adding -x
to the shabang (#!/bin/bash -x
).
I recently came across a new way, adding set -euxo pipefail
right under the shabang, as in:
#!/bin/bash
set -euxo pipefail
What is the main difference between the two ways of debugging? Are there times you would prefer one above the other?
As a freshman, after reading here, I couldn't extract such conclusion.
Best Answer
First, I'm afraid that explanation of
-o
option served by http://explainshell.com is not entirely correct.Given that
set
is a bulit-in command, we can see its documentation withhelp
by executinghelp set
:As you can see
-o pipefail
means:But it doesn't say:
Write the current settings of the options to standard output in an unspecified format.
Now,
-x
is used for debugging as you already know it and-e
will stop executing after the first error in the script. Consider a script like this:The
echo bye
line will never be executed when-e
is used becausenon-existent-command
does not return 0:Without
-e
the last line would be printed because even though an error happened we didn't tellBash
to automatically exit:set -e
is often put at the top of the script to make sure that the script will be stopped when the first error is encountered - for example, if downloading a file failed it doesn't make sense to extract it.