Passing options

So far, we have seen in the first chapter how to read parameters from the user. Also, you can pass options. So, what are options? And how are they different from parameters?

Options are characters with a single dash before them.

Check out this example:

$ ./script1.sh -a

The -a is an option. You can check from your script if the user entered this option; if so, then your script can behave in some manner.

You can pass multiple options:

$ ./script1.sh -a -b -c

To print these options, you can use the $1, $2, and $3 variables:

#!/bin/bash
echo $1
echo $2
echo $3

We should check these options, but, since we haven't discussed conditional statements yet, we will keep it simple for now.

Options can be passed with a value, like this:

$ ./script1.sh -a -b 20 -c

Here the -b option is passed with a value of 20.

As you can see, the variable $3=20, which is the passed value.

This might not be acceptable to you. You need $2=-b and $3=-c.

We will use some conditional statements to get these options correct.

#!/bin/bash
while [ -n "$1" ]
do
case "$1" in
-a) echo "-a option used" ;;
-b) echo "-b option used" ;;
-c) echo "-c option used" ;;
*) echo "Option $1 not an option" ;;
esac
shift
done

If you don't know about the while loop, it's not a problem; we will discuss conditional statements in detail in the coming chapters.

The shift command shifts the options one step to the left.

So, if we have three options or parameters and we use the shift command:

It's like an action to move forward while iterating over the options using the while loop.

So, in the first loop cycle, $1 will be the first option. After shifting the options, $1 will be the second option and so on.

If you try the previous code, you will notice that it still doesn't identify the values of options correctly. Don't worry, the solution is coming; just wait a little longer.