getopts

Optional option argument with getopts

非 Y 不嫁゛ 提交于 2019-11-26 09:09:12
问题 while getopts \"hd:R:\" arg; do case $arg in h) echo \"usgae\" ;; d) dir=$OPTARG ;; R) if [[ $OPTARG =~ ^[0-9]+$ ]];then level=$OPTARG else level=1 fi ;; \\?) echo \"WRONG\" >&2 ;; esac done level refers to parameter of -R , dir refers to parameters of -d when I input ./count.sh -R 1 -d test/ it works rightly when I input ./count.sh -d test/ -R 1 it works rightly but I want to make it work when I input ./count.sh -d test/ -R or ./count.sh -R -d test/ This means that I want -R has a default

Why does getopts only work the first time?

南楼画角 提交于 2019-11-26 08:35:53
问题 Why does this option only work the first time it\'s used, then ignored every other time? It\'s like it\'s being reset when the option is not used. Here\'s my function: testopts() { local var=\"o false\" while getopts \"o\" option; do case \"${option}\" in o) var=\"o true\" ;; esac done echo $var } When running it, it only returns true when passing the option for the first time. $ testopts o false $ testopts -o o true $ testopts -o o false 回答1: You need to add this line at top of your function

Using getopts inside a Bash function

丶灬走出姿态 提交于 2019-11-26 08:04:36
问题 I\'d like to use getopts inside a function that I have defined in my .bash_profile. The idea is I\'d like to pass in some flags to this function to alter its behavior. Here\'s the code: function t() { echo $* getopts \"a:\" OPTION echo $OPTION echo $OPTARG } When I invoke it like this: t -a bc I get this output: -a bc ? What\'s wrong? I\'d like to get the value bc without manually shifting and parsing. How do I use getopts correctly inside a function? EDIT: corrected my code snippet to try

How do I parse command line arguments in Bash?

强颜欢笑 提交于 2019-11-25 23:56:45
问题 Say, I have a script that gets called with this line: ./myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile or this one: ./myscript -v -f -d -o /fizz/someOtherFile ./foo/bar/someFile What\'s the accepted way of parsing this such that in each case (or some combination of the two) $v , $f , and $d will all be set to true and $outFile will be equal to /fizz/someOtherFile ? 回答1: Update: It's been more than 5 years since I started this answer. Thank you for LOTS of great edits/comments

Using getopts to process long and short command line options

♀尐吖头ヾ 提交于 2019-11-25 21:53:59
问题 I wish to have long and short forms of command line options invoked using my shell script. I know that getopts can be used, but like in Perl, I have not been able to do the same with shell. Any ideas on how this can be done, so that I can use options like: ./shell.sh --copyfile abc.pl /tmp/ ./shell.sh -c abc.pl /tmp/ In the above, both the commands mean the same thing to my shell, but using getopts , I have not been able to implement these? 回答1: There are three implementations that may be