set -eux instead set -x in Bash profile for global debugging

11,047

This is a matter of opinion, but I think set -eu is a bad idea for interactive use. Here’s what each one does:

  • set -e causes the shell to exit whenever a pipeline, list, or compound command exits with non-zero status;
  • set -u causes the shell to exit whenever it attempts to expand a parameter which isn’t defined.

In an interactive shell, this means that any mistake in a command would cause the shell to exit! For example, a typo in a command name, or rm with an incorrect file name, or echo $blah with an incorrect variable name...

set -e and set -u can be useful when writing shell scripts. In particular, set -e avoids compounding errors: as soon as a command fails, the script exits, which can avoid trouble from subsequent commands which don’t run in the context they expect.

Compared to your explanations, note that -e doesn’t protect you from executing code which would return a non-zero status; the command has to execute for it to return a non-zero status.

Share:
11,047

Related videos on Youtube

Admin
Author by

Admin

Updated on September 18, 2022

Comments

  • Admin
    Admin over 1 year

    When I work with Bash I love to do so with prominent debug mode, so each time I get a new machine I add to the end of ~/.profile the code set -x.

    I consider adding eu as well, so to have set -eux as a "best-practice'.

    If I understand the BR manual correctly

    1. e gives me the benefit of not-executing code that would eventually return a non-zero (typically erroneous) output.
    2. u - I didn't quite understand, the man says:

    Treat unset variables and parameters other than the special parameters ‘@’ or ‘*’ as an error when performing parameter expansion. An error message will be written to the standard error, and a non-interactive shell will exit.

    It sounds to me quite like e but also treating unsetted variables as error-causing and exits with a non-zero as well.

    Is my understanding here accurate and set -eux is better than just set -x in general for someone seeking best "typical" debugging out there?