Named Parameters In Bash

10-17-2018

Sometimes we need to pass multiple arguments to a shell script and often we don’t need to pass all arguments to our script everytime, that’s where named parameters comes in. With named parameters we can pass something like “–school hard knocks” to our script. However in bash this isn’t something we have available to us by default, but there is a cool little function that can help.

The idea is to pass your named parameter as an argument starting with two dashes (–) followed by the name of the parameter a space and the parameter value. The function looks like this:

my-script.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/bin/bash

environment=${environment:-production}
school=${school:-is out}

while [ $# -gt 0 ]; do

if [[ $1 == *"--"* ]]; then
param="${1/--/}"
declare $param="$2"
# echo $1 $2 // Optional to see the parameter:value result
fi

shift
done

echo $environment $school

(credit to the StackOverflow poster for the start of this solution)

To call this script passing parameters:

1
2
./my-script.sh --environment dev
>> dev is out

OR

1
2
./my-script.sh --random-parameter random-value
>> production is out

The script is assigning both school and environment to the default values that are assigned at the beginning of the script. We also have a new parameter cleverly named random-parameter that has a value of random-value.

It’s pretty simple but let’s go through each section of the script to understand what’s happening.

At the beginning we assign a couple variables some default values, this way if the user doesn’t pass the values our script will at least continue to run successfully. By assigning the variable name back to itself we’re saying that the script should take any parameter that is passed if not use the default. The default value is identified with the ‘[parameter name]:-[default value].

1
2
environment=${environment:-production}
school=${school:-is out}

Next we have a simple while loop that first evaluates if we have any passed parameters, if so it will proceed with looping.

1
2
3
while [ $# -gt 0 ]; do
...
done

Inside of our while loop we loop over each of the parameters looking for the “–” indicator, once we find one we assign the string directly after the “–” to the parameter name and the string directly following to it’s value.

...
if [[ $1 == *"--"* ]]; then
    v="${1/--/}"
    declare $v="$2"
    # echo $1 $2 // Optional to see the parameter:value result
fi
...

This is a simple way to pass parameters to a shell script, indicating the name and value with a simple identifier.