Magazine

Understanding Getopts

Posted on the 29 March 2021 by Satish Kumar @satish_kumar86

Command-line parameters passedalongwith commands arealsocalled positional parameters. Many times, we need to pass options such as-fand-valong with a positional parameter.

Let’s look at an example for passing the-xor-yoptions along with commands.

Write shell scriptgetopt.sh, as follows:

getopt.sh
#!/bin/bash 
 
USAGE="usage: $0 -x -y" 
 
while getopts :xy: opt_char 
do 
  case $opt_char in 
  x) 
    echo "Option x was called." 
    ;; 
  y) 
    echo "Option y was called. Argument called is $OPTARG" 
    ;; 
  ?) 
    echo "$OPTARG is not a valid option." 
    echo "$USAGE" 
    ;; 
  esac 
done

Execute this program:

$ ./getopt.sh

You will learn about the switch and case statements in the next chapters. In this script, if option-xis passed, a case statement forxwill be executed. If the-yoption is passed, then a case statement for-ywill be executed. If no option is passed, there will not be any output on the screen.

Let us run script with different options::

$ ./getopt.sh -x

The output is as follows:

Output:
Option y was called. Argument called is my_file.
$ ./getopt.sh -x -y my_file
Output:
Option x was called.
Option y was called. Argument called is my_file.
$ ./getopt.sh -y my_file -x
Output:
Option y was called. Argument called is my_file.
Option x was called.

Back to Featured Articles on Logo Paperblog