2014-04-01 52 views
0

我試圖創建一個bash命令,輸入一個介於1和12之間的數字,並且它使用了switch命令,但在bash shell中是case命令。我只是需要確保我有正確的想法去做這件事,或者如果我完成了關閉使用bash腳本並使用case語句

#!/bin/bash 
1="January" 
2="February" 
3="March" 
4="April" 
5="May" 
6="June" 
7="July" 
8="August" 
9="September" 
10="October" 
11="November" 
12="December" 
case "1" in 
print "$1" 
case "2" in 
print "$2" 
case "3" in 
print "$3" 
case "4" in 
print "$4" 
case "5" in 
print "$5" 
case "6" in 
print "$6" 
case "7" in 
print "$7" 
case "8" in 
print "$8" 
case "9" in 
print "$9" 
case "10" in 
print "$10" 
case "11" in 
print "$11" 
case "12" in 
print "$12" 
echo "Please enter a number 1 through 12" 
read input_variable 
echo "$input_variable" 
+1

'1 = 1月份'也不是有效的變量賦值。如果你想通過'$ 12'設置'$ 1',你可以運行:'set - January February March April April June July August September'。 –

+2

...但是,既然你使用bash,更好的答案是一個數組:'declare -a months =(January February ... etc ...);讀-r input_variable; echo「$ {months [$((input_variable - 1))}」'。對於這種用法,'case'陳述是過分的。 –

+0

@CharlesDuffy我認爲是一樣的 - 我在我的答案中添加了一個基於數組的示例。 –

回答

3

我不敢說你有點偏離。這裏的東西更像是有點:

#!/bin/bash 

echo "Please enter a number 1 through 12" 
read input_variable 

case $input_variable in 
    1) 
     echo "January" 
     ;; 
    2) 
     echo "February" 
     ;; 
    3) 
     echo "March" 
     ;; 
    4) 
     echo "April" 
     ;; 
    # 5), 6) etc. 
    *) # anything else 
     echo "not recognised" 
     ;; 
esac 

@Charles達菲是正確的,你實際上並不需要爲這個case。你可以使用這樣的數組:

編輯:當我寫這篇文章時,我看到了@devnull的改進!

#!/bin/bash 

echo "Please enter a number 1 through 12" 
read input 

months=(January February March April May June July August September October November December) 

[ $input -gt 0 -a $input -le 12 ] && echo "${months[input-1]}" 

,或者如果你願意,使用在陣列(感謝@chepner)開始虛擬條目

months=("" January February March April May June July August September October November December) 

[ ! -z "${months[input]}" ] && echo "${months[input]}" 
+0

有一種感覺我離得很遠,但是謝謝你的迴應會試一試 – user3438676

+0

作爲一種化妝品變體,你可以添加一個虛擬元素數組開始到服務器爲月0;那麼你不需要從輸入中減去一個來作爲索引。 – chepner

+0

@chepner謝謝,我已經添加它作爲另一種選擇 –

0

使用:

read -p "Enter a number between 1 and 12: " input 

,因爲它簡化了代碼。然後使用:

case $input in 

...等湯姆·費內奇指出

但是,是的case語句更針對同一類型的結果的測試,但結果證明什麼執行與它根據不同的動作成爲。你在這裏迴應一切,所以是將字符串存儲在一個數組中,並根據輸入輸出它。