Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between ${var} and ${var-}

Tags:

bash

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!
like image 663
olopopo Avatar asked May 18 '16 17:05

olopopo


People also ask

What is the difference between $VAR and ${ var?

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.

What is ${ 2 in bash?

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.

What does ${ 1 mean in bash script?

${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.

What is ${ 0 in bash?

${0} is the first argument of the script, i.e. the script name or path.


1 Answers

${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

Why use ${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.]

Documentation

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]

like image 53
John1024 Avatar answered Sep 23 '22 23:09

John1024