Shell processing command-line options getopts

Source: Internet
Author: User

Getopts is a built-in command of the shell, typically used to handle shell command-line options, but cannot handle long options (such as--prefix=/home, etc.) directly.

Getopts has 2 parameters, the first parameter is a string, including the character and ":", each character is a valid option, if the character is followed by ":", indicating that the character has its own parameters. The second parameter is used to store the acquired options.

The shell provides 2 built-in variables for getopts:

Optarg: The parameters of the corresponding options are stored;

Optind: Stores the location of the next processing option in the original $*;

Instance:

#!/bin/bashecho $*while getopts  ": A:BC"  opt     #第一个冒号表示忽略错误do          case  $opt  in                 a )  echo  $OPTARG                      echo $ Optind;;                 b )   echo  "b  $OPTIND";;                 c )   echo  "c  $OPTIND";;                 ? )   echo  "Error"                      exit 1;;         esacdoneecho  $OPTINDshift  $ (($OPTIND  - 1)) #通过shift  $ (($OPTIND  - 1)), the $* only retains the parameters to remove the contents of the option, which can then be processed by normal shell programming. echo $0echo $*

Execute command:./getopts.sh-a 11-b-C
-A 11-b-C
11
3
B 4
C 5
5
./getopts.sh


Resources:

http://blog.csdn.net/li385805776/article/details/16981541

Shell processing command-line options getopts

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.