Bash : automatically exit the script if a variable is not set
Use the command set -u for testing variable initialization.
"set -u
, an alias of set -o nounset
, is used
to exit the script everytime it's trying to call a not initialized variable.
By putting this command at the top of your script, you can avoid to manually test your variables before each use.
Automatically test if a variable is set
#!/bin/bash echo "No error before set: "$test; if [ "$test" == "" ]; then echo "We can see that this variable is not initialized"; fi # Starting here, the script will exit # if a variable is not initialized. set -u; # Disable the automatic testing set +u; echo "This line will not provoke any error"$test; # Enable the automatic testing set -u; echo "An error will be triggered : "$test; echo "This line will not be displayed";
Result of this script
$ ./script.sh No error before set: We can see that this variable is not initialized This line will not provoke any error ./script.sh: line 20: test : variable without link
Another use of set for testing return codes of commands.