I've come across a script that uses
VAR1=${1:-8}
VAR2=${2:-4}
I can see from some other questions and playing with some code that
VAR1=${VAR2:-8}
will create VAR1
with a value of whatever VAR2
is, if it exists. If VAR2
is unset, then VAR1
will default to value 8, and VAR2
will remain unset. That is, after this command, echo VAR2
will not return anything.
So then, my question is what the first line of code does. Since variable names cannot begin with numbers, VAR1
is clearly not being set to 1 or any variable named 1. Surely there is reason for this, and it's not just a bit of pointless obfuscation?
-
needed? What does the minus even mean? – gMale May 06 '22 at 02:11${var:-word}
expands toword
if$var
is unset or empty; otherwise, it expands to$var
.${var:+word}
expands toword
if$var
is set and not empty; otherwise, it expands to the empty string.${var:?word}
generates an error containingword
and terminates if$var
is unset or empty; otherwise, it expands to$var
. See also the POSIX standard and your shell's manual. – Kusalananda May 06 '22 at 05:56