Skip to content

Instantly share code, notes, and snippets.

@izabera
Last active June 6, 2025 08:18
Show Gist options
  • Save izabera/bd37b1ad1f2cc5f2f9c0ad3b35ec5710 to your computer and use it in GitHub Desktop.
Save izabera/bd37b1ad1f2cc5f2f9c0ad3b35ec5710 to your computer and use it in GitHub Desktop.

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

  1. shells are required to show a diagnostic message on syntax errors and expansion errors, but not necessarily what caused it

  2. in bash dash zsh & mksh

  3. dash and zsh only print "bad substitution"

  4. ksh and yash don't like this trick at all and (incorrectly) just error out unconditionally

  5. nothing in the standard prevents a shell from supporting spaces in expansions as an extension, making this not an error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment