bash脚本参数

时间:2009-05-06 02:52:20

标签: bash scripting parameters

我需要编写 bash脚本,并希望它解析格式为无序参数

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

有没有一种简单的方法可以实现这一点,或者我几乎坚持使用1美元,2美元,3美元?

5 个答案:

答案 0 :(得分:10)

你想要getopts

答案 1 :(得分: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

答案 2 :(得分:2)

如何实现短期和短期的一个很好的例子并排的长开关是mcurl:

http://www.goforlinux.de/scripts/mcurl/

答案 3 :(得分:1)

Bash有一个getops功能,如前所述,可以解决你的问题。

如果你需要更复杂的东西,bash也支持位置参数(订购$ 1 ... $ 9,然后$ {10} .... $ {n}),你必须提出自己的逻辑处理这个输入。一个简单的方法是将一个开关/案例放在for循环中,迭代参数。您可以使用处理输入的两个特殊bash vars中的任何一个:$* or $@

答案 4 :(得分:-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
相关问题