I’m new to shell scripting and I came across these expressions
${var:-val} and ${var-val}
${var:+val} and ${var+val}
${var:=val} and ${var=val}
so how are they evaluated and what are the differences between them
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
These are all various forms of parameter expansion with alternatives:
${var:-val}is replaced byvalifvaris unset or null,${var}otherwise (sovalis a “default value”);${var:=val}first assignsvaltovarifvaris unset or null, and then (in all cases) is replaced by${var};${var:+val}is replaced with nothing ifvaris unset or null,valotherwise.
Omitting the : drops the “or null” part of all these definitions.
This is all described in the bash(1) manpage, and in POSIX.
Some examples might help:
unset a
echo "${a:-default}"
produces default, as does echo "${a-default}".
a=
echo "${a:-default}"
again produces default, but echo "${a-default}" outputs a blank line.
a=test
echo "${a:-default}"
produces test, as does echo "${a-default}".
unset a
echo "${a:=default}"
produces default, and a is now default (as confirmed by echo "${a}").
The + form might seem strange, but it is useful when constructing variables in several steps:
PATH="${PATH}${PATH:+:}/blah/bin"
will add : before /blah/bin only if PATH is non-empty, which avoids having a path starting with :.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0