This article was reproduced from: Http://yejinxin.github.io/parse-shell-options-with-getopt-command
In a previous article, we described how to use the shell's built-in getopts command to help us with Shell scripting options and parameters, with the drawback that we could only handle short options and not handle long options. Below, this article is going to cover the getopt command, which can handle both short and long options.
First, the getopt command is not a standard UNIX command, but it comes with the majority of Linux distributions, and if not, it can be downloaded and installed from the GETOPT website.
In the older version of Getopt, there are some bugs, not easy to use, in later versions of the problem solved, we call the Getopt enhanced version. With the-t option, we can check whether the current getopt is an enhanced version, with a return value of 4, which indicates an enhanced version.
#getopt -T#echo $?4#getopt -Vgetopt (enhanced) 1.1.4
The getopt command differs from the getopts command in that it actually helps us with the normalization of parameters. Specific usage, such as the following script:
#!/bin/bash#echo [email protected]The #-o or--options option is followed by an acceptable short option, such as AB:C::, which means that the acceptable short option is-a-b-C, where the-a option has no parameters, the-B option must be followed by the parameter, and the-C option has an optional parameterThe #-l or--long option is followed by an acceptable long option, separated by commas, with the meaning of the colon being the same as the short option.#-n option followed by option parsing error when prompted by the script nameARGS=' Getopt-o ab:c::--long along,blong:,clong::-N' Example.sh '--"[Email protected]"`If[$? != 0];ThenEcho"Terminating ..."Exit 1Fi#echo $ARGS#将规范化后的命令行参数分配至位置参数 ($1,$2,...)Eval Set--"${ARGS}"WhileTrueDo case"$"In-a|--along)Echo"Option a";Shift;; -b|--blong)Echo"Option B, argument$";Shift 2;; -c|--clong)Case"$"Inch"")Echo"Option C, no argument";shift 2 ;; *) echo "Option C, argument $2< span class= "S2"; shift 2; ;; esac shift break * echo "Internal error!" exit 1 ;; esacdone #处理剩余的参数 for arg in [email protected]do echo processing $arg "done
It is important to note that, like the-C option above, the following are optional parameters, if you need to pass a parameter to the-C option, you must use this method:
#./getopt.sh -b 123 -a -c456 file1 file2 Option b, argument 123Option aOption c, argument 456processing file1processing file2#./getopt.sh --blong 123 -a --clong=456 file1 file2 Option b, argument 123Option aOption c, argument 456processing file1processing file2
This article from the night of the alarming blog, reproduced please retain the source
To parse the shell Script's command-line option "Go" using the getopt command