Shell脚本循环命令行开关和参数

时间:2013-05-09 18:42:22

标签: linux bash shell

我正在尝试编写一个bash脚本,它将检查命令行开关并使用switch参数的下一个参数。

示例:

sh myprogram.sh -s switchArg -p programArg start

在我的脚本中,我试图以这种方式循环:

if [ "$#" -gt 2 ]
then
{
    i=1
    for arg in "$@"
    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 个答案:

答案 0 :(得分:2)

你可以使用“shift”来删除第一个参数。
例如:

arg1=$1; shift
arg2=$1