What means these declarations in bash script:
PREFIX=${1:-daily}
PROFILE=${2:-backup}
What means these declarations in bash script:
PREFIX=${1:-daily}
PROFILE=${2:-backup}
The key here is to understand what Parameter-Expansion ${PARAMETER:-WORD}
syntax means here,
${PARAMETER:-WORD}
If the parameter PARAMETER is unset (never was defined) or null (empty), this one
expands to WORD, otherwise it expands to the value of PARAMETER, as if it
just was ${PARAMETER}
In your case the ${PARAMETER}
being the positional arguments passed to a function or script,
Use the below script for a better understanding,
myTestFunction() {
PREFIX=${1:-daily}
PROFILE=${2:-backup}
printf "PREFIX value %s PROFILE value %s\n" "$PREFIX" "$PROFILE"
}
myTestFunction "some" "junk"
myTestFunction
which produces a result as
$ bash script.sh
PREFIX value some PROFILE value junk
PREFIX value daily PROFILE value backup
Also see the expanded debugger version of the script as
$ bash -x script.sh
+ myTestFunction some junk
+ PREFIX=some
+ PROFILE=junk
+ printf 'PREFIX value %s PROFILE value %s\n' some junk
PREFIX value some PROFILE value junk
+ myTestFunction
+ PREFIX=daily
+ PROFILE=backup
+ printf 'PREFIX value %s PROFILE value %s\n' daily backup
PREFIX value daily PROFILE value backup
how shell substitutes the values to the variables when $1
or $2
is not passed.
The syntax is generally used when by default you want to configure a variable with a certain value at the same time make it dynamically configurable also.
Assigns value of first argument to PREFIX variable if this first argument exist, "daily" if it does not.
It means, assign the first argument
(if present), else daily
to variable PREFIX
and assign the second argument
(if present), else backup
to variable PROFILE
eg:
$ cat file.sh
#!/bin/bash
PREFIX=${1:-daily}
PROFILE=${2:-backup}
echo $PREFIX
echo $PROFILE
For the following command line args given, output would be like:
$ ./file.sh
daily
backup
$ ./file.sh abc
abc
backup
$ ./file.sh abc xyz
abc
xyz