文章出處

  getopts命令順序的對現有的shell參數變量進行處理,每調用一次getopts,他只處理在命令中檢測到的參數中的一個,處理完所有的參數后,以大于0的退出狀態退出,因此,getopts非常適宜用在循環中解析所有命令參數
getopts命令的格式為 getopts optstring variable 
  其中optstring值與getopt命令中使用的相似,在選項字符串中列出郵箱選項字母,如果選項字母需要參數放在命令行中定義的variable中getopts命令使用兩個環境變量,環境變量OPTARG包含的值表示getopts停止處理時在參數列表中的位置,這樣,處理完選項后可以繼續處理其它命令行參數.

  文件名為 test19.sh 

 1 #!/bin/bash
 2 # sinmple demonstration of the getopts command
 3 
 4 while getopts :ab:c opt
 5 do
 6   case "$opt" in
 7   a) echo "Found the -a option" ;;
 8   b) echo "Found the -b option, with value $OPTARG";;
 9   c) echo "Found the -c option" ;;
10   *) echo "Unknow option :$opt";;
11  esac
12 done

運行 sh test19.sh -ab test1 -c 

輸出:

Found the -a option
Found the -b option, with value test1
Found the -c option

 

  while語句定義getopts命令,指定要查找哪些命令行選項以及每次迭代中存儲它們的變量名,在本例中,可以看到case語句的使用有些特別之處,當getopts命令解析命令行選項時,會將打頭的破折號去掉,所以在case定義中不需要破折號
  getopts命令具有許多很好的特性,首先,現在可以在參數值中包含空格

運行 sh test19.sh -b "test1 test2" -a 

輸出:

Found the -b option, with value test1 test2
Found the -a option

另一個好特性是選項字母和參數值中間可以沒有空格

運行 sh test19.sh -abtest1 

輸出:

Found the -a option
Found the -b option, with value test1

getopts命令正確的將-b選項后面的test1值解析出來,getopts命令還有一個好特性就是將在命令行中找到的未定義的選項都綁定為一個單一的輸出--問號

運行 sh test19.sh -d 

輸出: Unknow option :? 

 

  getopts命令知道核實停止處理選項,將參數留給你處理,getopts每個處理選項,環境變量OPTIND的值會增加1,當達到getopts處理的末尾時,可以使用shift命令和OPTIND值進行操作來移動到參數

文件名: test20.sh 

#!/bin/bash
# processing options and parameters with getopts

while getopts :ab:cd opt
do
  case "$opt" in
  a) echo "Found the -a option" ;;
  b) echo "Found the -b option ,with value $OPTARG";;
  c) echo "Found the -c option";;
  d) echo "Found the -d option";;
  *) echo "Unknow option:$opt";;
esac
done
shift $[ $OPTIND - 1 ]

count=1
for param in "$@"
do 
  echo "Parameter $count:$param"
  count=$[ $count + 1 ]
done

運行 sh test20.sh -a -b test1 -d test2 test3 test4 

輸出:

Found the -a option
Found the -b option ,with value test1
Found the -d option
Parameter 1:test2
Parameter 2:test3
Parameter 3:test4

 


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()