Skip to Content
Learning Linux Shell Scripting
book

Learning Linux Shell Scripting

by Ganesh Sanjiv Naik
December 2015
Beginner
306 pages
5h 2m
English
Packt Publishing
Content preview from Learning Linux Shell Scripting

Understanding getopts

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

Let's learn the example for passing the –x or –y options along with commands. Write the 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 be learning switch and case statements in the next chapters. In this script, if option –x is passed, a case statement for x will be executed. ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Linux Shell Scripting - Second Edition

Learning Linux Shell Scripting - Second Edition

Ganesh Sanjiv Naik

Publisher Resources

ISBN: 9781785286216