0
0
Bash Scriptingscripting~5 mins

set -u for undefined variable errors in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does set -u do in a Bash script?

set -u makes the script stop and show an error if you try to use a variable that has not been set or defined. This helps catch mistakes early.

Click to reveal answer
beginner
Why is using set -u helpful when writing scripts?

It prevents bugs caused by typos or missing variables by stopping the script immediately when an undefined variable is used. This makes scripts safer and easier to debug.

Click to reveal answer
intermediate
How can you safely use a variable that might be undefined when set -u is active?

You can provide a default value using ${VAR:-default}. This way, if VAR is not set, the script uses default instead of stopping.

Click to reveal answer
beginner
What happens if you run this script with set -u enabled?<br>
#!/bin/bash
set -u
echo "Hello $NAME"

The script will stop with an error because NAME is not defined. set -u catches this and prevents the script from continuing.

Click to reveal answer
beginner
How do you enable set -u in a Bash script?

Add the line set -u near the top of your script, usually after the #!/bin/bash line.

Click to reveal answer
What does set -u do in a Bash script?
APrints all variables used in the script
BAllows undefined variables without errors
CStops the script if an undefined variable is used
DDisables all error messages
How can you avoid errors with set -u when a variable might be missing?
AUse <code>${VAR:-default}</code> to provide a default value
BIgnore the error and continue
CUse <code>unset VAR</code> before using it
DDisable <code>set -u</code> temporarily
Where should you place set -u in your Bash script?
AAt the very end of the script
BAt the top, after the <code>#!/bin/bash</code> line
CAnywhere in the middle
DOnly inside functions
What error will you get if you use an undefined variable with set -u?
Abash: variable_name: unbound variable
Bbash: variable_name: command not found
Cbash: syntax error near unexpected token
DNo error, script continues
If you want to allow undefined variables without errors, what should you do?
AUse <code>set -e</code> instead
BAlways define all variables
CUse <code>set -x</code>
DDo not use <code>set -u</code>
Explain what set -u does in a Bash script and why it is useful.
Think about how scripts behave when variables are missing.
You got /3 concepts.
    Describe how to safely use variables that might not be set when set -u is enabled.
    Look at variable expansion syntax.
    You got /3 concepts.