Current Issue


Table of contents

CD-ROM

Sys Admin and The Perl Journal CD-ROM version 12.0

Version 12.0 delivers every issue of Sys Admin from 1992 through 2006 and every
issue of The Perl Journal from 1996-2002 in one convenient CD-ROM!

Order now!

Sys Admin Magazine > Archives > 2000 > 0007

Processing Command-Line Options in the Shell

Ed Schaefer

If your shell scripts are to move beyond the ad hoc, you will need to process command-line options beyond the simple:

unixscript $1 $2 $3
And, if other users and software developers are going to use your scripts, a concise approach to processing command-line options will simplify using these options and trapping errors.

This article presents three advanced methods of processing command-line options. The first method is using the UNIX built-in command, getopts, to do the parsing. The other two methods, coding parameters and keyword=value, require writing code to process the command-line options using a “while” loop and the shift command.

Using getopts

System V supports a built-in command-line parser command, getopts, for both the Bourne and Korn shells. The getopts command placed in a loop will parse single character flags, provided that the flag exists in the argument string succeeding the getopts command and the flag is preceded by a dash.

the general form of getopts is:

getopts optionstring name
where “optionstring” is one or more valid option letters that getopts recognizes and “name” is a variable that getopts shifts into with each execution. If an option requires an argument, such as “-z argument” a colon follows the option letter.

With each execution of getopts, the next command-line option value is placed in variable name for processing. Each execution also bumps the OPTIND counter by one. Using OPTIND allows other command-line options to be processed after the getopts loop terminates.




MarketPlace

�Six Sigma� Certified?
100% Online-Six Sigma Certificate From Villanova -Find Out More Now.

PMP Certification-Online
Nation's Leading Online PMP Course From Villanova-Find Out More Now.

Flowcharts from C/C++ code -- Free trial download
Understand C/C++ code in less time. A new team member ? Inherited legacy code ? Get up to speed faster with Crystal Flow for C/C++. Code-formatting improves readability. Flowcharts are integrated with code browser. Export flowcharts to Visio.

Automate Software Builds with Visual Build Pro
Easily create an automated, repeatable process for building and deploying software.

Wanna see your ad here?