1

What means these declarations in bash script:

PREFIX=${1:-daily}

PROFILE=${2:-backup}
Mohamed Ben HEnda
  • 2,686
  • 1
  • 30
  • 44

3 Answers3

4

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.

Inian
  • 80,270
  • 14
  • 142
  • 161
2

Assigns value of first argument to PREFIX variable if this first argument exist, "daily" if it does not.

Laurent G
  • 397
  • 8
  • 16
1

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
Arjun Mathew Dan
  • 5,240
  • 1
  • 16
  • 27