0

我有一个这样的 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 

我需要添加另一个可能具有多个参数值的参数,例如

 setup.sh -localsource PATH  -locbranches one two three 

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

提前致谢

4

2 回答 2

0

我注意到您必须编写大量逻辑来处理最简单的命令行参数机制,我可能会建议使用bash getopts 功能

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

setup.sh -localsource PATH one two three 

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

setup.sh -localsource PATH -locbranch one -locbranch two -locbranch three
于 2012-12-13T09:20:30.943 回答
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
于 2012-12-13T09:29:43.873 回答