How to parse argument parameters in bash shell?

This script will help you to understand how to parse argument parameters in bash shell.

Lets start by declaring some default values for parameters. This is to handle the case in which the argument parameters are not passed to the script.

#!/bin/sh
export ALPHA="DEFAULT_ALPHA"
export BETA="DEFAULT_BETA"

 

The next we add a case statement, and handle each argument specifically.  In case we find a match with the parameter name, we set the environment variable with the next token passed in the input.  After that shift operation removes the argument and argument parameter value from the stack, and proceeds to processing the next argument parameter.

while true ; do
  case "$1" in
    --alpha) export ALPHA="$2" ; shift 2 ;;
    --beta) export BETA="$2" ; shift 2 ;;
    *) break ;;
  esac
done

Next lets print the values once we are done with parsing, and store the above script to a file bash_command_parsing.sh.  Change the mode on this script so that it can be run as executable.

echo "GOT ALPHA $ALPHA"
echo "GOT BETA $BETA"

 

Lets run the script. First we run it without passing any argument, and then we pass it both arguments.

$> ./bash_command_parsing.sh
GOT ALPHA DEFAULT_ALPHA
GOT BETA DEFAULT_BETA
$> ./bash_command_parsing.sh --alpha 0.4 --beta 0.2
GOT ALPHA 0.4
GOT BETA 0.2

 

Note that the argument parsing is very unforgiving in this example, and bails out as soon as it encounters  any unhandled parameters.  In the first example, script passes the first argument correctly, and then bails out as soon as it sees a unhandled parameter.  In the second example, the the first parameter itself is unhandled, so script would not even try to parse the second parameter.

$> ./bash_command_parsing.sh --alpha 0.4 --beta1 0.2
GOT ALPHA 0.4
GOT BETA DEFAULT_BETA
 $> ./bash_command_parsing.sh --alpha1 0.4 --beta 0.2
GOT ALPHA DEFAULT_ALPHA
GOT BETA DEFAULT_BETA
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s