Home > Net >  Bash : error handling in "export" instruction
Bash : error handling in "export" instruction

Time:05-19

I'm using bash for writing a script.

I use set -ein order to have the script exit (in error) when a line results in an error (i like this approach, that I find less error prone). I almost always combine it with set -u for also "raising" an error when it is attempted to read an undefined variable.

It has worked like a charm since a long time. But today, I found a bug in my script that I could not catch with "set -eu" before, because this does not seem to raise an error like usual.

For the following, I will use the false command that always returns an error (in my script this is another personnal command, but this makes it easier for you to reproduce).

set -eu 
A=$(false)

The code above exits bash with an error. Cool this is what I expect.

BUT :

set -eu 
export A=$(false)

does not raise any error, bash is totally fine with it ! It even sets the variable A with an empty string, so further reads of $A will not raise an error either !

This is really weird for me, is there a way of getting the expected behaviour, maybe another option for ```set`` ?

I can do this for having it raise an error, but I will have to write it this way every time, so it is less useful for catching bugs :

set -eu 
A=$(false)
export A=$A

God bash is complicated :-)

CodePudding user response:

You're not getting an error because the export itself is successful. I can't find explicit documentation of the behavior, but command substitution when building the arguments to another command seems to be one of the special cases where a non-zero exit status doesn't make set -e trigger.

  • Related