In bash version 4.4.12, when I type:

set -e

at the command prompt, the shell exits, returning 128.

Why does this happen when set -u is fine?

  • 2
    Do you have anything fancy in your prompt, or in a debug command? – Stephen Kitt Apr 15 '17 at 6:24
  • 3
    Do you have something set up to run code in between commands? What does echo $PROMPT_COMMAND give? echo $PS1? trap? – Michael Homer Apr 15 '17 at 6:25
  • My fix was to add local -; set +e inside the function which $PROMPT_COMMAND called. This restores the original $- when the function returns. – Tom Hale Apr 15 '17 at 10:24

If, for example, you have a command that is returning a non-zero exit status as part of the expansion of PROMPT_COMMAND (which is executed before printing the prompt in bash), then this will trigger the shell to exit immediately when you set the errexit option with set -e.

Another possibility is that there is a DEBUG trap set that returns a non-zero exit status. A DEBUG trap is however executed before a command is invoked, so it would not cause the shell to exit immediately as you press Enter after set -e, but instead before launching the next command.

With set -u you set the nounset shell option. This option will issue cause the shell to issue an error if you try to expand any unset variable apart form $@ and $*. It will not cause the shell to exit, unless set -e is also in effect.

With set -u in effect and an unset variable in PS1, the shell will exit as soon as you set the errexit option with set -e.

  • $PS1 doesn't support running commands. Also, the command could be running via a DEBUG trap. – Tom Hale Apr 15 '17 at 7:20
  • 1
    @TomHale Thanks for the DEBUG trap reminder. If PS1 contains a command substitution that returns a non-zero exit status, the shell will exit if set -e is set. Try it with PS1=$(false). – Kusalananda Apr 15 '17 at 7:22
  • You're right on the DEBUG trap, however: PS1=$(false); set -e; echo OK is just fine. (The expansion of $() occurs only once, and would occurred while set +e was in effect.) – Tom Hale Apr 15 '17 at 7:34
  • 1
    @TomHale Ah, you are correct. I meant PS1='$(false)', but that will not make a difference. I will update. Thanks! – Kusalananda Apr 15 '17 at 7:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.