Understanding getopts

Command-line parameters passed along with commands are also called positional parameters. Many times, we need to pass options such as -f and -v along with a positional parameter.

Let's look at an example for passing the -x or-y options along with commands.

Write shell script getopt.sh, as follows:

#!/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 -x is passed, a case statement for x will ...

Get Learning Linux Shell Scripting - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.