10

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
     prompt="Y/n"
     default=Y
  elif [ "${2:-}" = "N" ]; then
     prompt="y/N"
     default=N
  else
     prompt="y/n"
     default=
  fi

  read -p "$1 [$prompt] " REPLY </dev/tty
αғsнιη
  • 41,407

1 Answers1

16

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.

DopeGhoti
  • 76,081