Florian Heinle
9 months
Claus-Theodor Riegg
8 years
Kim Klotz
11 months
Moritz Kraus
1 year
Claus-Theodor Riegg
1 year
Stefan Xenopol
1 year

Parameter naming and checking in shell script

Posted About 1 year ago. Visible to the public.

It is a good idea to use named variables for storing parameters of a script or function. We can use parameter expansion to either set a default or check mandatory arguments

Mandatory parameter

hello() {
    NAME=${1:?provide name as first parameter}
    echo "Hello $NAME!"
}

$ hello  # $?=1
bash: 1: provide name as first parameter

$ hello Foo # $?=1
Hello Foo!

Parameter with default

hello() {
  NAME=${1:-Marvin}
  echo "Hello $NAME!"
}

$ hello  # $?=0
Hello Marvin!

$ hello Foo # $?=1
Hello Foo!

Moritz Kraus
Last edit
About 1 year ago
Deleted user #4941
License
Source code in this card is licensed under the MIT License.