Transferred from: http://yejinxin.github.io/parse-shell-options-with-getopts-command/
Standard UNIX commands generally offer a number of options, with the user providing specific options and parameters, in the form of a command line, as follows:
command -options parameters filename
Getopts is a shell built-in command that helps us to handle command-line options so that our scripts can be consistent with UNIX commands. The usage format for getopts is:
getopts option_string variable
For specific examples, directly on the script:
#!/bin/bashQUIET=VERBOSE=DEVICE=LOGFILE=/tmp/defaultusage(){Echo"Usage: ' basename $ ' [-QV] [-l LOGFILE]-D DEVICE input_file [input_file2 ...]"Exit 1}[$#-eq 0]&& usage#option_string以冒号开头表示屏蔽脚本的系统提示错误, handle the error message yourself.#后面接合法的单字母选项, if there is a colon after the option, it means that the option must be followed by a specific parameterWhileGetopts:qvd:l: OPTIONDoCase$OPTION in Q)QUIET=y;; V)VERBOSE=y;; D)DEVICE=$OPTARG# $OPTARG is a special variable that represents the specific parameters of the option;; L)LOGFILE=$OPTARG;;\?)#如果出现错误, then parse to? Usage;;EsacDone# $OPTIND is a special variable that represents the first few options, with an initial value of 1Shift$(($OPTIND-1))#除了选项之外, the script must meet at least one parameterIf[$#-eq 0 ]then Usagefiif [-Z "$DEVICE" ]then #该脚本必须提供-d option echo "You must specify DEVICE with-d option "exitfiecho " you chose the Following options: " echo "quiet= $QUIET verbose= $VERBOSE device= $DEVICE logfile= $LOGFILE" for file in [email protected] #依次处理剩余的参数 do< Span class= "K" > echo "processing $file" done
The above is an example of the use of the getopts command, you can see that the getopts command does not support the long option. Note that there is another Linux command getopt, which can support the long option, but not the built-in commands, the UNIX version and the Linux version of the usage is not the same, use see another article.
command-line options for parsing shell scripts using the getopts command