In an earlier article, we discussed how to pass command line arguments to shell script and ac...em using positional parameters. In this, we will see how to use the getopts command to pass command line options to shell scripts. Command line options are the options or switches passed to a command. For example, -l, -r, -t are some examples of the command line options passed to the ls command.
Command line options can be classified into 3 types:
- Options which does not take arguments:
- Options which take arguments:
- Options + Additional command line arguments:
The syntax of the getopts command is:
-> optstring - the string which contains the list of options expected in the command line
-> name - the variable name which is used to read the command line options one by one.
There are environment variables used in this command:
Let us now discuss with examples how to use the getopts command.
1. Options without arguments:
Let us create a bash shell script to display the current date and month. This script will take 2 command line options:
Running the shell script with options:
2. Options with arguments:
In this example, let us update the same script so that "-d" option can take a value. If "-d" is provided a value n, the date and month displayed will be n days from the current date(GNU Date). For example, if the current date is 30th Aug, and if a value of 2 is provided with "-d", the date and month displayed will be "01" and "Sep".
Similarly, if you want both the options to contain arguments, it should be: "d:m:"
3. Options with arguments + Additional command line parameters:
In this script, the script will be updated to also accept some additional command line arguments. An additional argument will be provided for which a welcome message will be printed.
OPTIND contains the index of the next command line option. Keep in mind, all the command line options provided to the shell script will be present in the variables $1, $2 , $3 and so on. How can we now distinguish where the command line options get over and from where the additional arguments start? This is where the OPTIND helps. In this example, when the getopts has processed, OPTIND will contain 4, pointing to the next(4th) argument. And hence, in order to access the command line arguments, it is better if we flush of all the command line options and its arguments prior to the additional arguments. And hence the shift command.
* Positional parameters in a shell script