'What's the meaning ${1:-}?
Could you help me explain the expression in BASH script ?
${1:-}
I never see it before, so I try some about it.
echo ${1:-}
echo ${1}
I cant see any difference.
Thank you very much!!!
Solution 1:[1]
From the man page:
${parameter:-word}
Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
Solution 2:[2]
It doesn't have much purpose. ${1-} is relevant when set -u is enabled, in which case it's another hack similar to ${1+"$1"} to prevent throwing errors in the event a parameter with a value that is expected to be possibly unset is dereferenced.
$ ( f() { printf '<%s> <%s>\n' $# ${1-}; }; set -u; f )
<0> <>
$ ( f() { printf '<%s> <%s>\n' $# $1; }; set -u; f )
-bash: $1: unbound variable
Adding the colon will expand the alternate when the parameter is unset or null. In either case, when the expansion is unquoted the result will always be no args (regardless of the IFS value). It isn't uncommon for people to be unaware of the difference between the - and :- PE operators due to the unfortunate way it's specified in Bash's manpage.
As usual, I suggest never using set -u in scripts. Use it only temporarily if you're one of those that find it useful for debugging.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | phs |
| Solution 2 |
