2012-03-04 221 views
3

我想在我的bash腳本中解析傳入選項,並將值保存在變量中。 這是我的代碼:變量賦值在case語句中(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 

然而,內部「情況」的陳述必須是命令行命令,所以無法根據需要進行分配。什麼是正確的方法來做到這一點?

回答

8

圍繞=運營商刪除空格:

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

;; 我不得不刪除第一個$,它的工作原理 – 2015-11-18 15:36:47

+0

我的錯誤是用這樣的^ h的bash腳本語言)$主機= 「$ OPTARG」 – 2016-10-18 10:30:01

0

您還需要改變optstring - 的c選項需要遵循一個冒號,如果要收集它的參數:

while getopts "H:w:c:" flag 
0

當我創建一個腳本來練習if/then/else和case語句時,我採取了一種稍微不同的方法。順便說一句,如果你安裝cowsay;

sudo apt-get install cowsay 

and fortune;

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 
    ~ 
這就是爲什麼我恨:)