Option Parsing in Shell Scripts

In the previous example, you manually handled the options passed to your script. In this second example, you will explore a second method, using the getopts command. The syntax of the getopts command is as follows:

getopts option-string
						var
					

Here option-string is a string consisting of all the single character options getopts should consider and var is the name of the variable that the option should be set to. Usually var is a variable named OPTION.

The process by which getopts parses the options given on the command line is as follows:

1.
getopts examines all the command-line arguments, looking for arguments starting with the - character.
2.
When an argument starting with the - character is found, it compares ...

Get Sams Teach Yourself Shell Programming in 24 Hours, Second Edition now with O’Reilly online learning.

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