How does "${2:-}" work in an 'if-then-else example' below? Somehow I cannot help but think that being ${2:-} it means the second argument, but I am curious what the colon(:) and dash(-) after the digit 2 mean?

  if [ "${2:-}" = "Y" ]; then
  elif [ "${2:-}" = "N" ]; then

  read -p "$1 [$prompt] " REPLY </dev/tty

The syntax ${VAR:-default} evaluates to the value of VAR or, if it is unset or null, it evaluates to the text after the hyphen (in this case, default); the syntax ${VAR- default} is similar shortened of the a similar function only for when the variable is unset. $2 is a positional parameter, so your statement is testing the value of the second argument, and if it is not set, using an empty value as a default.

Why use an empty default, since that would have the same effect as a plain $2? Because under set -u (equivalent to set -o nounset), substituting an unset variable causes an error: if there are less than 2 parameters, $2 errors out. But ${2:-} won't error out, because it explicitly substitutes the empty string if the parameter is unset or null.

  • bash reference – Jeff Schaller May 12 '16 at 16:59
  • 1
    which begs the question, how ${2:-} differs from ${2} which also has an empty expansion if it's empty or unset. – Gilles 'SO- stop being evil' May 12 '16 at 22:24
  • 2
    I suppose it depends on whether the context of this section of the script has set -u in place (: – DopeGhoti May 12 '16 at 22:30
  • It has a 'set -o nounset' at the very beginning of the script, would that be the same as 'set -u'? – nocturnalmonkey May 13 '16 at 15:20
  • Yes, the latter is shorthand for the former. – DopeGhoti Jul 30 '18 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.