Bash – set -u usage not working as expected

bashshellshell-script

I am learning how to efficiently use different set options in my script and came across set -u that appears to be perfect for exiting my script if a variable does not get set properly (ex. deleting users). According to the man page, set -u and set -e does the following…

-e  Exit immediately if a command exits with a non-zero status.
-u  Treat unset variables as an error when substituting.

I created a test script to test this functionality, but it does not appear to be working as expected. Perhaps someone could better explain my issue to me and where I am mis-interpreting? Test script is below. Thank you.

set -e
set -u
testing="This works"
echo $?
echo ${testing}
testing2=
echo $?
echo ${testing2}
testing3="This should not appear"
echo $?
echo ${testing3}

I expect the script to display 0 and "This works", and then fail as ${testing2} is not set.

Instead I am displayed 0 and "This works", follow by 0 and then 0 This should not appear

Can anyone provide some knowledge? Thank you.

Best Answer

From "man Bash":

A parameter is set if it has been assigned a value. The null string is a valid value. Once a variable is set, it may be unset only by using the unset builtin command.

When you do testing2= you are setting the variable to the null string.

Change that to unset testing2 and try again.


The set -e does not help in this case as an assignment never has an exit code of 1. Try this to see that the last command executed (the assignment) has an exit code of 0, or read this question:

$ false; a=""; echo $?
0

And I also believe that the use of set -e is more a problem that a solution.

What may get an error with the use of unset variables is set -u:

#!/bin/bash
set -u
testing="This works"
echo ${testing}
unset testing2
echo ${testing2}
testing3="This should not appear"
echo ${testing3}

Will output:

$  ./script.sh
This works
./script.sh: line 9: testing2: unbound variable
Related Question