case语句中的变量赋值(bash)

时间:2012-03-04 16:14:34

标签: bash command-line switch-statement

我正在尝试解析bash脚本中的传入选项,并将值保存在变量中。 这是我的代码:

#!/bin/bash 

while getopts "H:w:c" flag
do 
#  echo $flag $OPTIND $OPTARG
    case $flag in
    H) host = "$OPTARG"
    ;;
    w) warning = "$OPTARG"
    ;;
    c) critical = "$OPTARG"
    ;;
    esac
done

但是,'case'中的语句必须是命令行命令,所以我无法进行所需的赋值。这样做的正确方法是什么?

3 个答案:

答案 0 :(得分:9)

删除=运算符周围的空格:

case "$flag" in
  H) host="$OPTARG" ;;
  w) warning="$OPTARG" ;;
  c) critical="$OPTARG" ;;
esac

答案 1 :(得分:0)

您还需要更改optstring - 如果要收集其参数,c选项后面必须跟冒号:

while getopts "H:w:c:" flag

答案 2 :(得分:0)

在创建脚本来练习if / then / else和case语句时,我采用了稍微不同的方法。顺便说一下,如果你安装了cowsay;

    sudo apt-get install cowsay

和财富;

    sudo apt-get install fortune

您可以按原样使用此脚本,然后使用它来习惯在case语句中进行赋值或使用if / then / else语句。

    #!/bin/bash
    echo "Choose a character from the following list:"
    echo
    echo "1) Beavis"
    echo "2) Cow Hitting a Bong"
    echo "3) Calvin"
    echo "4) Daemon"
    echo "5) Dragon and Cow"
    echo "6) Ghostbusters"
    echo "7) Ren"
    echo "8) Stimpy"
    echo "9) Sodomized Sheep"
    echo "0) Mech and Cow"
    #
    echo
    read character
    echo
    #
    case "$character" in
      "1") file="beavis.zen.cow" ;;
      "2") file="bong.cow" ;;
      "3") file="calvin.cow" ;;
      "4") file="daemon.cow" ;;
      "5") file="dragon-and-cow.cow" ;;
      "6") file="ghostbusters.cow" ;;
      "7") file="ren.cow" ;;
      "8") file="stimpy.cow" ;;
      "9") file="sodomized-sheep.cow" ;;
      "0") file="mech-and-cow.cow" ;;
      *) clear; ./cowsay.sh;
    esac
      #
    #echo "var 'file' == $file"
    echo "What would you like your character to say?"
    echo "Alternatively, if you want your character to"
    echo "read you your fortune, type 'fortune'."
    read input_string
    #
    if [ $input_string = fortune ] ; then
      clear; $input_string | cowsay -f /usr/share/cowsay/cows/$file
    else
      clear; cowsay -f /usr/share/cowsay/cows/$file $input_string
    fi
    ~