I've seen some shell scripts that make use of this variable reference notation and I just can't find any info on it.
As far as my tests have gone it is just plainly the same.
Any clues?
$ uno=1
$ if [ -n "${uno}" ]; then echo yay\! ; fi
yay!
$ if [ -n "${uno-}" ]; then echo yay\! ; fi
yay!
Difference between Both: The variable $var is used to store the value of the variable and the variable $$val is used to store the reference of the variable.
It means "Use the second argument if the first is undefined or empty, else use the first". The form "${2-${1}}" (no ':') means "Use the second if the first is not defined (but if the first is defined as empty, use it)". Copy link CC BY-SA 2.5.
${1}, ${2}, … ${n} as positional arguments. ${#} the number of positional arguments for the current context. ${_} the last argument of the previous command executed. The ENVIRONMENT VARIABLES inherited from the calling shell.
${0} is the first argument of the script, i.e. the script name or path.
${uno-}
is an example of providing a default value in case the parameter uno
is unset.
If uno
is unset, we get the string that follows the -
:
$ unset uno
$ echo ${uno-something}
something
If uno
is merely the empty string, then the value of uno
is returned:
$ uno=""
$ echo ${uno-something}
$
If uno
has a non-empty value, of course, then that value is returned:
$ uno=Yes
$ echo ${uno-something}
Yes
${variable-}
?When proper operation of a script is important, it is common for the script writer to use set -u
which generates an error message anytime an unset variable is used. For example:
$ set -u
$ unset uno
$ echo ${uno}
bash: uno: unbound variable
To handle the special cases where one may want to suppress this message, the trailing -
can be used:
$ echo ${uno-}
$
[Credit for finding that the OP's full code used set -u
and its importance to this question goes to Benjamin W.]
From man bash
When not performing substring expansion, using the forms documented below (e.g., :-), bash tests for a parameter that is unset or null. Omitting the colon results in a test only for a parameter that is unset.
${parameter:-word}
Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted. [emphasis added]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With