2013-05-09 61 views
1

我想寫一個bash腳本,它將檢查命令行switchess並使用開關參數的下一個參數。shell腳本來循環命令行開關和參數

例子:

sh myprogram.sh -s switchArg -p programArg start 

在我的劇本我想循環是這樣:

if [ "$#" -gt 2 ] 
then 
{ 
    i=1 
    for arg in "[email protected]" 
    do 
     if [ "$arg" == "-s" ] || [ "$arg" == "-S" ] 
     then 
     { 
      i=$((i++)) 
      myArg=$i # This then gets used later in my script 
      continue 
     } 
     elif [ "$arg" == "-p" ] || [ "$arg" == "-P" ] 
     then 
     { 
     i=$((i++)) 
     myArg2=$i # This then gets used later in my script 
     continue 
     } 
     else 
     { 
     echo "illegal option: $arg" 
     } 
    done 

    do stuff 
} 
fi 

如何檢測開關,並使用第二天ARG爲的說法不管開關的數量是多少?

+1

看看http://stackoverflow.com/questions/192249/how-do-i -parse-command-line-arguments-in-bash和http://stackoverflow.com/questions/14152712/argument-parsing-in-bash和http://stackoverflow.com/questions/9271381/how-can-i -parse-long-form-arguments-in-shell和一大堆其他的...... – 2013-05-09 18:49:09

+0

謝謝,那看起來像金色的票。 – 2013-05-09 18:51:02

+1

你確實意識到'{'和'}'是不必要的,對吧?它們似乎讓你忘記了'for'循環中的'fi'。 – chepner 2013-05-09 19:04:56

回答

2

您可以使用「移動」,將刪除第一個參數..
例如:

arg1=$1; shift 
arg2=$1