getopts

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