1. Introduction to getopts
Thanks to the flexibility of shell command lines, write your ownCodeWhen judging, the complexity is relatively high. Use the Internal Command getopts to easily process command line parameters. The general format is:
Getopts options variable
Getopts is designed to run in a loop. Each time a loop is executed, getopts checks the next command line parameter and determines whether it is valid. Check whether the parameter starts with-, followed by a letter contained in options. If yes, the matching option letter will exist in the specified variable, and return the exit status 0. If-followed by the letter is not included in options,?And returns the exit status 0. If there is no parameter in the command line, or the next parameter does not start with-, it returnsNot 0.
Ii. Example
Cat ARGs
# ! /Bin/bash
While Getopts H: Ms Option
Do
Case " $ Option "In
H)
Echo "Option: H, Value $ Optarg "
Echo "Next Arg index: $ Optind ";;
M)
Echo "Option: M"
Echo "Next Arg index: $ Optind ";;
S)
Echo "Option: S"
Echo "Next Arg index: $ Optind ";;
\?)
Echo "Usage: ARGs [-H n] [-M] [-S]"
Echo "-H means hours"
Echo "-M means minutes"
Echo "-S means seconds"
Exit 1 ;;
Esac
Done
Echo "*** Do something now ***"
./Args-H 100-MS
Option: H, value: 100
NextArg index: 3
Option: m
NextArg index: 3
Option: S
NextArg index: 4
***DoSomething now ***
./Args-T
./Args: Illegal option -- t
Usage: ARGs [-H n] [-M] [-S]
-H means hours
-M means minutes
-S means seconds
Note:
1. getopts allows option stacking (for example,-MS)
2. To include a parameter, add the parameter H: ms after the corresponding option (for example, H ). At this time, the options and parameters must be separated by at least one blank character. Such options cannot be stacked.
3. If the parameter is not found after the parameter option is required, it is saved to the specified variable.?And write error messages to standard errors. Otherwise, write the actual parameters into special variables:Optarg
4. Another special variable:OptindTo reflect the next parameter index to be processed. The initial value is 1, which is updated every time getopts is executed.