34
if [ -n "${BASH-}" -o -n "${ZSH_VERSION-}" ] ; then
    hash -r 2>/dev/null
fi

Where can I find the reference on this? Thanks.

Ankur Agarwal
  • 23,692
  • 41
  • 137
  • 208

3 Answers3

45

Variables inside a ${...} are called « Parameter Expansion ».
Search for that term in the online manual, or the actual manual (line 792).
The ${var-} form is similar in form to ${var:-}. The difference is explained just one line before the :- expansion (line 810):

... bash tests for a parameter that is unset or null. Omitting the colon results in a test only for a parameter that is unset.

Thus, this form is testing only when a variable is unset (and not null), and replaces the whole expansion ${...} for the value after the -, which in this case is null.

Therefore, the ${var-} becomes:

  1. The value of var when var has a value (and not null).
  2. Also the value of var (the colon : is missing!) when var is null:'', thus: also null.
  3. The value after the - (in this case, null '') if var is unset.

All that is just really:

  1. Expand to '' when var is either unset or null.
  2. Expand to the value of the var (when var has a value).

Therefore, the expansion changes nothing about the value of var, nor it's expansion, just avoids a possible error if the shell has the option nounset set.

This code will stop on both uses of $var:

#!/bin/bash
set -u

unset var

echo "variable $var"
[[ $var ]] && echo "var set"

However this code will run without error:

#!/bin/bash
set -u

unset var
echo "variable ${var-}"
[[ ${var-} ]] && echo "var set"
5

Its a bash parameter expansion thats used for checking if a variable is not set

Explanation

When you use ${ZSH_VERSION-WORD} as opposed to $ZSH_VERSION in your bash script, bash will perform additional logic

if $ZSH_VERSION is set
then 
    simply use the value of $ZSH_VERSION as per normal

elseif

$ZSH_VERSION is NOT set 
then
    use value of WORD - which isnt provided in your case - so null

is used

References

Basic parameter expansion is covered in the man bash docs (line 939 of bash man page).

see: POSIX

also see this SO answer

Community
  • 1
  • 1
the_velour_fog
  • 2,094
  • 4
  • 17
  • 29
  • It is covered in the [Bash Manual](http://www.gnu.org/software/bash/manual/bash.html#Shell-Expansions), as BinaryZebra correctly points out in his answer. – Ben Voigt Sep 20 '15 at 02:49
  • thanks @Ben Voigt have removed incorrects parts of my answer. I agree binary zebras answer gives better explanation – the_velour_fog Sep 20 '15 at 03:08
3

Under normal circumstances, ${FOO-} behaves exactly the same as ${FOO}.

However, with set -u, expansion of unset variables becomes an error by default.

So ${FOO} could be an error, but ${FOO-} never will be.

o11c
  • 15,265
  • 4
  • 50
  • 75