2013-05-09 43 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