shell getopts 用法

C語言裏面有個getopt_long,可以獲取用戶在命令下的參數,然後根據參數進行不同的提示或者不同的執行。

在shell中同樣有這樣的函數或者用法吧,在shell裏面是getopts,也有一個getopt是一個比較老的。這次說getopts,我自己的一些用法和感悟。

首先先來一個例子吧:

[hello@Git shell]$ bash test.sh -a hello  
this is -a the arg is ! hello  
[hello@Git shell]$ more test.sh   
#!/bin/bash  

while getopts "a:" opt; do  
  case $opt in  
    a)  
      echo "this is -a the arg is ! $OPTARG"   
      ;;  
    \?)  
      echo "Invalid option: -$OPTARG"   
      ;;  
  esac  
done  

上面的例子顯示了執行的效果和代碼。
getopts的使用形式是:getopts option_string variable

getopts一共有兩個參數,第一個是-a這樣的選項,第二個參數是 hello這樣的參數。

選項之間可以通過冒號:進行分隔,也可以直接相連接,:表示選項後面必須帶有參數,如果沒有可以不加實際值進行傳遞

例如:getopts ahfvc: option表明選項a、h、f、v可以不加實際值進行傳遞,而選項c必須取值。使用選項取值時,必須使用變量OPTARG保存該值。

[hello@Git shell]$ bash test.sh -a hello -b  
this is -a the arg is ! hello  
test.sh: option requires an argument -- b  
Invalid option: -  
[hello@Git shell]$ bash test.sh -a hello -b hello -c   
this is -a the arg is ! hello  
this is -b the arg is ! hello  
this is -c the arg is !   
[hello@Git shell]$ more test.sh   
#!/bin/bash  

while getopts "a:b:cdef" opt; do  
  case $opt in  
    a)  
      echo "this is -a the arg is ! $OPTARG"   
      ;;  
    b)  
      echo "this is -b the arg is ! $OPTARG"   
      ;;  
    c)  
      echo "this is -c the arg is ! $OPTARG"   
      ;;  
    \?)  
      echo "Invalid option: -$OPTARG"   
      ;;  
  esac  
done  
[hello@Git shell]$  

執行結果結合代碼顯而易見。同樣你也會看到有些代碼在a的前面也會有冒號,比如下面的
情況一,沒有冒號:

[hello@Git shell]$ bash test.sh -a hello  
this is -a the arg is ! hello  
[hello@Git shell]$ bash test.sh -a  
test.sh: option requires an argument -- a  
Invalid option: -  
[hello@Git shell]$ more test.sh   
#!/bin/bash  

while getopts "a:" opt; do  
  case $opt in  
    a)  
      echo "this is -a the arg is ! $OPTARG"   
      ;;  
    \?)  
      echo "Invalid option: -$OPTARG"   
      ;;  
  esac  
done  
[hello@Git shell]$

情況二,有冒號:

[hello@Git shell]$ bash test.sh -a hello  
this is -a the arg is ! hello  
[hello@Git shell]$ bash test.sh -a   
[hello@Git shell]$ more test.sh   
#!/bin/bash  

while getopts ":a:" opt; do  
  case $opt in  
    a)  
      echo "this is -a the arg is ! $OPTARG"   
      ;;  
    \?)  
      echo "Invalid option: -$OPTARG"   
      ;;  
  esac  
done 

情況一輸入 -a 但是後面沒有參數的的時候,會報錯誤,但是如果像情況二那樣就不會報錯誤了,會被忽略。
getopts option_string variable
當optstring以”:”開頭時,getopts會區分invalid option錯誤和miss option argument錯誤。

invalid option時,varname會被設成?,OPTARGoptionmissoptionargumentvarname: OPTARG是出問題的option。
如果optstring不以”:“開頭,invalid option錯誤和miss option argument錯誤都會使varname被設成?,$OPTARG是出問題的option。

參考:http://xingwang-ye.iteye.com/blog/1601246
http://blog.csdn.net/xluren/article/details/17489667

發佈了51 篇原創文章 · 獲贊 20 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章