Magazine

Understanding Default Parameters

Posted on the 30 March 2021 by Satish Kumar @satish_kumar86

Many times, we maypasscertain parameters from the command line, but, sometimes, we may not pass any parameters at all. We may need to initialize certain default values to certain variables.

We will review this concept through the following script.

Create scriptdefault_argument_1.sh, as follows:

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

Execute the script and check the output:

$ chmod +x default_argument_1.sh One
$ ./default_argument_1.sh OneOne
$ ./default_argument_1.shdefault

Create another default_argument_2.sh script:

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

The output is as follows:

Output:
satish@linuxconcept$ ./default_argument_2.sh one two
one
two
satish@linuxconcept$
satish@linuxconcept$ ./default_argument_2.sh one
one
one
satish@linuxconcept$

We executed the script two times:

  • When we passed two arguments, thenvariable1was$1andvariable2was$2.
  • In the second case, when we passed only one argument, then$1was taken as the default argument for$2. Therefore,variable1was used as the default forvariable2. If we do not give a second parameter, then the first parameter is taken as the default for the second parameter.

You Might Also Like :

Back to Featured Articles on Logo Paperblog

These articles might interest you :