you know ${var?error message here}
in sh? it produces an error and prints the message if $var
is undefined. otherwise it expands to $var
introducing: ${var+${error message here}}
if $var
is defined, the spaces in the error message cause a syntax error, which prints the message. otherwise it expands to nothing
(and similarly for all other outer expansions)
it reliably1 works2 perfectly3 in every4 posix sh5
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02
where expression consists of all characters until the matching '}'.
In each case that a value of word is needed (based on the state of parameter, as described below), word shall be subjected to tilde expansion, parameter expansion, command substitution, and arithmetic expansion. If word is not needed, it shall not be expanded.
next: recursive expansions
previous: reading a file line by line in your shell
Footnotes
-
shells are required to show a diagnostic message on syntax errors and expansion errors, but not necessarily what caused it ↩
-
in bash dash zsh & mksh ↩
-
dash and zsh only print "bad substitution" ↩
-
ksh and yash don't like this trick at all and (incorrectly) just error out unconditionally ↩
-
nothing in the standard prevents a shell from supporting spaces in expansions as an extension, making this not an error ↩