Shell script中使用getopt例子

來源:互聯網
上載者:User

Shell script中使用getopt例子 使用getopt可以非常方便的格式話選項跟對應的參數,例子如下   www.2cto.com  Shell代碼  #!/bin/bash  set -- `getopt -q ab:c "$@"`  while [ -n "$1" ]  do    case "$1" in    -a)       echo "option -a";;    -b)       value="$2"        echo "option -b with para $value"  shift;;    -c) echo "option -c";;    --) shift        break;;    *) echo "$1 not option";;   esac   shift  done  count=1  for para in "$@"  do   echo "#$count=$para"   count=$[$count+1]  done   ./test -ab test1 -cd test2 test3 test4 結果:option -a option -b with para 'test1' option -c #1='test2' #2='test3' #3='test4'  getopt 用法: getopt options optstring parameters  對於./test -ab test1 -cd "test2 test3" test4 這樣的參數類型,getopt是無能為力的。這就需要getopts了   www.2cto.com  Shell代碼  #!/bin/bash  while getopts :ab:c opt  do   case $opt in   a) echo "-a option";;   b) echo "-b option with value $OPTARG";;   c) echo "-c option";;   *) echo $opt not a option;;   esac  done   OPTARG 環境變數存放對應選項的參數 ./test -ab "hello,world" -cdefg 結果: -a option -b option with value hello,world -c option ? not a option ? not a option ? not a option ? not a option  命令參數的處理 Shell代碼  #!/bin/bash  while getopts :ab:cd opt  do   case $opt in   a) echo "-a option";;   b) echo "-b option with value $OPTARG";;   c) echo "-c option";;   d) echo "-d option";;   *) echo $opt not a option;;   esac  done  count=1  shift $[$OPTIND-1]  for para in "$@"  do  echo "#$count=$para"  count=$[$count+1]   done   ./test -abtest1 -cd test2 test3 test4 結果:   www.2cto.com  -a option -b option with value test1 -c option -d option #1=test2 #2=test3 #3=test4 OPTIND環境變數存放getopts命令剩餘的參數列表當前位值 用法:getopts optstring variable 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.