CompTIA Linux+ free question 8 / 10 · Domain 4: Automation, Orchestration, and Scripting
A backup script must not continue when the variable BACKUP_DIR is unset or null. It should write a message to standard error and exit with a non-zero status. Which parameter expansion does the Bash manual describe for that?
- ${BACKUP_DIR:?BACKUP_DIR is not set}, which writes the message to standard error and exits
- ${BACKUP_DIR:=/var/backup}, which assigns a default word to the variable when it is unset or null
- ${BACKUP_DIR:+/var/backup}, which substitutes a word when the variable is set and not null
- ${BACKUP_DIR:-/var/backup}, which substitutes a default word when the variable is unset or null
Show the answer and explanation
Answer: A
Why this is correct
The Bash manual describes ${parameter:?word} as an error check: if the parameter is null or unset, the shell writes the expansion of word, or a message to that effect, to standard error and, if it is not interactive, exits with a non-zero status. The forms :-, := and :+ substitute or assign a value, and none of them stops a script.
Why the other options are wrong
"${BACKUP_DIR:-/var/backup}, which substitutes a default word when the variable is unset or null" … The manual describes the :- form as substituting the expansion of word if the parameter is unset or null. The script goes on with the default value and prints no error.
"${BACKUP_DIR:=/var/backup}, which assigns a default word to the variable when it is unset or null" … The manual describes the := form as assigning the expansion of word to the parameter and using it as the final value. The script goes on with the assigned value and prints no error.
"${BACKUP_DIR:+/var/backup}, which substitutes a word when the variable is set and not null" … The manual describes the :+ form as substituting nothing if the parameter is null or unset, and the word otherwise. It never writes an error message or exits.
Key points
In ${parameter:OPword}, :- substitutes a default, := assigns a default, :? stops with an error, and :+ substitutes only when the parameter has a value. Without the colon, only a missing parameter is tested.
Go to the CompTIA Linux+ practice app (10 free questions; purchase unlocks all questions)