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 ...
Get Linux and Unix Shell Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.