在bash中捕获单个参数的多个值

时间:2012-12-13 09:13:33

标签: bash

我有一个像这样的bash脚本:

usage="setup.sh [-localsource path to dir] [-help]";

 for i in $@
    do
        if [ "$localSourceOpt" = 1 ]
        then
            localSource=$i
            localSourceOpt=0;
        fi
        if [ "$i" = "-localsource" ]
        then
            localSourceOpt=1;
        fi
        if [ "$i" = "-help" ]
        then
            echo "$usage";
            exit;
        fi
    done

需要参数,例如

setup.sh -localsource PATH 

我需要的是添加另一个MIGHT有多个参数值的参数,例如

 setup.sh -localsource PATH  -locbranches one two three 

我应该怎样做才能捕获为参数“-locbranches”传递的值

提前致谢

2 个答案:

答案 0 :(得分:0)

我注意到你需要编写很多逻辑来处理最简单的命令行参数机制,我建议改为使用bash getopts functionality

这使得单个参数选项工作变得微不足道。对于多个参数,它不能很好地工作,你必须引用args,例如-option "1 2 3"。但是在以下场景中处理多个参数。

setup.sh -localsource PATH one two three 

即。 one two three未链接到任何命令行选项。另一种方法是为每个参数指定选项,例如

setup.sh -localsource PATH -locbranch one -locbranch two -locbranch three

答案 1 :(得分:0)

您可以使用4种情况进行切换(-localsource,-locbranches,-help和default),并且在每种情况下都应该输入一种状态,

for i in $@; do
  case "$i" in

   "-help") echo "$usage"
            ;;
   "-localsource") STATE="localsource"
                 ;;
   "-locbranches") STATE="locbranches"
                 ;;
   *) 
          if [ "$STATE" == "localsource" ]; then
             PATH=$i
          elif [ "$STATE" == "locbranches"]; then
             # do something with argv from locbrances
          else
             echo "Wrong state!"
          fi
          ;;
  esac
done