What is the difference between $ {var} and $ {var-}

I have seen some shell scripts that use this variable reference notation, and I just can't find information about it.

As for my tests, it's just the same thing.

Any clues?

$ uno=1 $ if [ -n "${uno}" ]; then echo yay\! ; fi yay! $ if [ -n "${uno-}" ]; then echo yay\! ; fi yay! 
+6
source share
2 answers

${uno-} is an example of providing a default value if uno not set.

If uno not specified, we get the line following - :

 $ unset uno $ echo ${uno-something} something 

If uno is just an empty string, uno returned:

 $ uno="" $ echo ${uno-something} $ 

If uno has a non-empty value, of course, then this value is returned:

 $ uno=Yes $ echo ${uno-something} Yes 

Why use ${variable-} ?

When the script is working correctly, it is important that the script writer use set -u , which generates an error message at any time when an undefined variable is used. For instance:

 $ set -u $ unset uno $ echo ${uno} bash: uno: unbound variable 

To handle special cases where it may be necessary to suppress this message, you can use the final - :

 $ echo ${uno-} $ 

[Confirm that OP complete code is used by set -u , and its meaning for this question belongs to Benjamin W.]

Documentation

From man bash

If you do not perform substring expansion using the forms documented below (for example :-), bash checks for an invalid or null parameter. Lowering the colon leads to testing only for a parameter that is not set.

$ {parameter: -word}
Use default values . If the parameter is not specified or is null, the word is replaced. Otherwise, the value of the parameter. [highlighted by me]

+5
source

In the Bash manual, about parameter extension :

${parameter:-word}

If the parameter is not specified or is null, the word is replaced. Otherwise, the parameter value will be replaced.

In your case, word is an empty string and the colon is omitted. Without a colon, the check is performed only for cancellation, but not for zero, so ${uno-} equivalent to checking if uno (see How to check if a variable is set in Bash? ), And if not, expand it to empty strings - ensuring that the extension is not canceled.

It depends on the context, for which it is useful; in your example, it really doesn't matter.

Turns off the script context where set -u is used - see John 1024 answer for details.

+3
source

All Articles