I. Introduction of GETOPTS
Because of the flexibility of the shell command line, the complexity is higher when you write code judgments. Command-line arguments can be easily handled using the internal command getopts. The General format is:
Getopts Options Variable
Getopts is designed to run in a loop, and each time a loop is executed, getopts checks the next command-line argument and determines if it is legitimate. That is, check whether the parameter starts with a--followed by a letter contained in the options. If it is, put the matching option letter in the specified variable variable and return exit status 0; If-the following letter is not included in the options, it is stored in the variable . , and returns exit status 0 if no arguments are already in the command line, or if the next parameter does not start with-the exit status is not 0 .
Ii. Examples of Use
Cat args
#!/bin/bash
While getopts h:ms option
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
./args-h 100-ms
Option:h, Value 100
Next arg index:3
Option:m
Next arg index:3
Option:s
Next arg index:4
Do something 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 options to be stacked together (e.g.-ms)
2. If you want to take parameters, the corresponding options should be added after: (such as h after the need to add parameter h:ms). At this point the options and parameters are separated by at least one white space character, so options cannot be stacked.
3. If the parameter is not found after the option that requires it, it is stored in the given variable, and an error message is written to the standard error. Otherwise, the actual parameters are written to the special variable:optarg
4. Another special variable:optind, which reflects the next parameter index to be processed, the initial value is 1, and is updated each time the getopts is executed.
Linux command getopts