Parameter naming and checking in shell script

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 About 1 year ago