getopts
为base shell的内置命令,提供shell的参数扩展,能够获取shell脚本的选项,并且获取到shell脚本选项后边所跟的参数,并且能够在脚本中调用。
getopts optstring name [arg]
1.optstring定义脚本能够使用的参数
2.只支持短选项,不支持长选项。
3.如果想使用选项后面的参数,只需在选项后面加冒号(:)即可
4.默认情况下只能获取一个参数
eg1:
- [root@localhost ~]# cat test.sh
- #!/bin/bash
- getopts a OPT
- echo $OPT
- [root@localhost ~]# ./test.sh -a
- a
*如果想使用选项后面的参数,只需在选项后面加冒号(:)即可
eg2:
- [root@localhost ~]# cat test.sh
- #!/bin/bash
- getopts a: OPT
- echo $OPT
- echo $OPTARG
- [root@localhost ~]# ./test.sh -a "this is a"
- a
- this is a
*如果不想让其输出错误信息,秩序在所有选项之前加上冒号(:)即可
eg3:
- [root@localhost ~]# cat a.sh
- #!/bin/bash
- getopts a: OPT
- echo $OPT
- echo $OPTARG
- [root@localhost ~]# ./a.sh -b
- ./a.sh: illegal option -- b
- ?
- [root@localhost ~]# cat a.sh
- #!/bin/bash
- getopts :a: OPT
- echo $OPT
- echo $OPTARG
- [root@localhost ~]# ./a.sh -b
- ?
- b
*如果想使用多个选项,需要使用循环语句
eg4:
- [root@localhost ~]# cat a.sh
- #!/bin/bash
- while getopts ":a:b:" OPT;do
- case $OPT in
- a)
- echo $OPT
- echo $OPTARG
- ;;
- b)
- echo $OPT
- echo $OPTARG
- ;;
- *)
- echo "wrong option"
- ;;
- esac
- done
- [root@localhost ~]# ./a.sh -a "this is a"
- a
- this is a
- [root@localhost ~]# ./a.sh -b "this is b"
- b
- this is b
- [root@localhost ~]# ./a.sh -c "this is c"
- wrong option
转载于:https://blog.51cto.com/liufeily/874500