Bash脚本参数

14

我需要编写一个Bash脚本,并希望它解析以下格式的无序参数

scriptname --param1 <string> --param2 <string> --param3 <date>

有没有简单的方法可以实现这个,还是我只能使用$1、$2、$3?

5个回答

10

5
getopts不支持以双横线(--)开头的长选项,而getopt支持长选项,但使用和阅读起来都相当糟糕。 - Cameron
好的观点 - 如果长开关是必须的,那么getopts不是正确的工具。 - Lance Richardson
3
这个答案如果加上具体内容或例子会更好,而不只是一个链接。 - Vincent Scheib

8
while [[ $1 = -* ]]; do
    arg=$1; shift           # shift the found arg away.

    case $arg in
        --foo)
            do_foo "$1"
            shift           # foo takes an arg, needs an extra shift
            ;;
        --bar)
            do_bar          # bar takes no arg, doesn't need an extra shift
            ;;
    esac
done

“do_foo "$2"” 应该改为 “do_foo "$1"” 吗? - xx77aBs
@xx77aBs,是的,应该可以! - lhunath

2

1

Bash有一个getops函数,如之前所述,可能可以解决您的问题。

如果您需要更复杂的内容,bash还支持位置参数(有序$1 ... $9,然后是${10} .... ${n}),您将不得不想出自己的逻辑来处理此输入。一种简单的方法是在for循环内部放置一个switch/case,迭代参数。您可以使用两个特殊的bash变量之一来处理输入:$*或$@


-1
#!/bin/bash

# Parse the command-line arguments
while [ "$#" -gt "0" ]; do
  case "$1" in
    -p1|--param1)
      PARAM1="$2"
      shift 2
    ;;
    -p2|--param2)
      PARAM2="$2"
      shift 2
    ;;
    -p3|--param3)
      PARAM3="$2"
      shift 2
    ;;
    -*|--*)
      # Unknown option found
      echo "Unknown option $1."

      exit 1
    ;;  
    *)
      CMD="$1"
      break
    ;;
  esac
done 


echo "param1: $PARAM1, param2: $PARAM2, param3: $PARAM3, cmd: $CMD"

当我执行这个操作时:

./<my-script> --param2 my-param-2 --param1 myparam1 --param3 param-3 my-command

它会输出你所期望的结果:

param1: myparam1, param2: my-param-2, param3: param-3, cmd: my-command

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接