Read more

Parameter naming and checking in shell script

Moritz Kraus
April 21, 2023Software engineer at makandra GmbH

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!

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot
Posted by Moritz Kraus to makandra Operations (2023-04-21 10:38)