Understanding default parameters

Many times we may pass certain parameters from the command line; sometimes, we may not pass any parameters at all. We may need to have certain default values to be initialized to certain variables.

We will understand this concept by the following script.

Create a default_argument_1.sh script as follows:

#!/bin/bash
MY_PARAM=${1:-default}
echo $MY_PARAM

Execute the script and check:

$ chmod +x default_argument_1.sh One
$ ./default_argument_1.sh One
One
$ ./default_argument_1.sh
default

Create another default_argument_2.sh script:

#!/bin/bash
variable1=$1
variable2=${2:-$variable1}
echo $variable1
echo $variable2

Output:

We executed the script two times:

  • When we passed two arguments, then variable1 was $1 and variable2

Get Learning Linux Shell Scripting now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.