While dealing with this I came up with the following. We encapsulate all the procedure inside a function that takes all the arguments given to the script. Then, it iterates over all the arguments and whenever it find one that starts with double hyphen --arg1
it assigns the following argument arg2
to a global variable with the name of the first argument arg1="arg2"
. Next, it shifts the arguments' positions until it finish with all arguments.
#------ arguments_test.sh ------
#!/bin/bash
pararser() {
# Define default values
name=${name:-"name_def"}
lastName=${lastName:-"lastName_def"}
# Assign the values given by the user
while [ $# -gt 0 ]; do
if [[ $1 == *"--"* ]]; then
param="${1/--/}"
declare -g $param="$2"
fi
shift
done
}
pararser $@
echo "My name is " $name $lastName
In this way we can define default values if they are not passed.
$ arguments_test.sh
> My name is name_def lastName_def
$ arguments_test.sh --name Foo --lastName Bar
> My name is Foo Bar
Some references
- The main procedure was found here.
- More about passing all the arguments to a function here.
- More info regarding default values here.
- More info about
declare
do $ bash -c "help declare"
.
- More info about
shift
do $ bash -c "help shift"
.