SHELL脚本学习总结(第二话)getopts命令

@@@    getopts命令

getopts命令内建于bash shell。

getopts命令的格式如右:getopts optstring variable

                      optstring定义的内容与getopt命令完全相同。

但是其输出内容与getopt命令完全不同。

例子如下:

$ getopt ab:cd -a -b test1 -cd test2 test3    ###getopt输出例
-a -b test1 -c -d -- test2 test3

$ getopts ab:cd -a -b test1 -cd test2 test3   ###getopts输出例1
-bash: getopts: `-a': not a valid identifier

$ getopts ab:cd -a
-bash: getopts: `-a': not a valid identifier  ###getopts输出例2

$ getopts ab:cd a                             ###getopts输出例3
                                              ###回车后为不输出任何内容

为什么会由以上结果,我也不清楚。希望有懂的朋友可以助我解惑。

 

@@@    getopts在shell脚本中的用法

以下是一个简单的例子:

$ cat getopts.sh
#!/bin/bash
# simple demonstration of the getopts command
#
echo
while getopts ab:c opt                    ###通过whlie循环将选项通过getopts格式化成opt变量
do
case "$opt" in
a) echo "Found the -a option" ;;
b) echo "Found the -b option, with value $OPTARG";;    ###$OPTARG变量指的是选项后的参数
c) echo "Found the -c option" ;;
*) echo "Unknown option: $opt";;
esac
done
$

输出结果:

$ ./getopts.sh -ab test1 -c
Found the -a option
Found the -b option, with value test1
Found the -c option

$ ./getopts.sh -b "test1 test2" -a                  ###可以完美识别''双引号
Found the -b option, with value test1 test2
Found the -a option
$

$ ./getopts.sh -d                                   #输入未定义的选项后显示的错误信息
cat: invalid option -- 'd'
Try 'cat --help' for more information.

$ ./getopts.sh -d                                   #在ab:c之前加上:变成:ab:c以后getopts能                 
Unknown option: ?                                   #将所有未定义的选项统一输出成问号
 

 

以上,是我今天的学习总结。

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值