O'Reilly logo

Linux and Unix Shell Programming by David Tansley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

20.2. getopts

Getopts allows you to write code that can easily handle multiple command line arguments. Getopts is used to bring some form of standard in command line processing. After all, scripts should have the ability to conform to the standard format of command options files.

20.2.1. An example getopts script

Getopts is better understood with an example. Here is a simple getopts script that will take the following options or arguments.

-a Set the variable ALL to true
-h Set the variable HELP to true
-f Set the variable FILE to true
-v Set the variable VERBOSE to true

As with all variable settings we always assume the worst so initially set the variables to their false state:

							$ pg getopt1 !/bin/sh #getopt1 # set the vars ALL=false HELP=false ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required