| [ | Date | | | 2020-01-31 18:45 -0500 | ] |
| [ | Mod. | | | 2020-02-14 11:19 -0500 | ] |
This article is about an idiom to set default values for variables in Bash shell scripts; that is, values that can be overridden by setting variables prior to running the script.
: "${ID:=value}"This will make it so that ID retains its value, if it had one, defaulting to value otherwise.
Explanation:
The form ${parameter:=word} will either:
parameter alone, if it was already set to a non-empty string value; orparameter to (the expansion of) word, otherwise.In both cases, the expression has the new value of the parameter variable.
the built-in command : does nothing, ignoring its arguments: it is used here to ignore the return value from the ${parameter:=word} construct;
there are double quotes around the construct to prevent possibly time-consuming, and useless, expansion of the variable's value (e.g., if it includes wildcards). This is flagged by program validator ShellCheck as SC2223 "This default assignment may cause DoS due to globbing. Quote it."
I wish this was a more widely-known idiom, so that programmers would not be confused by it.
Note: A previous version of this article complained about ShellCheck flagging the unquoted version of the construct, but I now believe the rationale for SC2223 is sensible.
Quick links: