码迷,mamicode.com
首页 > 其他好文 > 详细

[Bash] Create a Bash Script that Accepts Named Options with getopts

时间:2021-02-16 12:03:18      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:RoCE   get   imp   cas   options   flag   case   process   while   

Getopts

Let’s say you want to allow a user to pass a -v flag to turn on verbose logging in a script. Manually parsing out options passed to a script is difficult, but in this lesson, we’ll learn about getopts which makes it easy. We‘ll look at the limitations of using getopts (options must be in a format like -a or -ab ) as well as the importance of shifting processed options off of the argument array.

## ‘:a‘: if the opt is a
## ‘b:‘ if the opt is b and it has value as well
## ‘$OPTARG‘: is the value that passed in
## ‘\?‘: catch unknown opt
while getopts ‘:ab:‘ opt; do
    case "$opt" in
        a) echo "a found";;
        b) echo "b found and the value is $OPTARG";;
        \?) echo "unknow option";;
    esac
done

If we run it with:

./getopts.sh -a -b 123
## a found
## b found and the value is 123

If we run with some extra options we didn‘t handle:

bash % ./getopts.sh -a -b 123 -d -e -f 321
## a found
## b found and the value is 123
## unknow option
## unknow option
## unknow option

Shift

Remove the args we have processed.

## ‘:a‘: if the opt is a
## ‘b:‘ if the opt is b and it has value as well
## ‘$OPTARG‘: is the value that passed in
## ‘\?‘: catch unknown opt
while getopts ‘:ab:‘ opt; do
    case "$opt" in
        a) echo "a found";;
        b) echo "b found and the value is $OPTARG";;
        \?) echo "unknow option";;
    esac
done

shift $(( OPTIND -1 ))

for arg in $@; do
    echo "received arg $arg"
done 

If run it with:

./getopts.sh -a -b 123 abc def tsf 

## a found
## b found and the value is 123
## received arg abc
## received arg def
## received arg tsf

[Bash] Create a Bash Script that Accepts Named Options with getopts

标签:RoCE   get   imp   cas   options   flag   case   process   while   

原文地址:https://www.cnblogs.com/Answer1215/p/14398914.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!