除了語法錯誤@PSkocik指出,當你有一些相互排斥的if
條件,這是通常更清晰/更好地使用if ... elif...
,而不是一堆如果單獨if
塊:
if [ "$command" = "my-tweets" ]; then
node liri.js "$command"
elif [ "$command" = "do-what-it-says" ];then
node liri.js "$command"
elif [ "$command" = "spotify-this-song" ]; then
...etc
但是當你比較反對一堆可能的串/模式的單一字符串("$command"
),case
是一個更清晰的方式來做到這一點:
case "$command" in
"my-tweets")
node liri.js "$command" ;;
"do-what-it-says")
node liri.js "$command" ;;
"spotify-this-song")
...etc
esac
此外,當幾個不同的案例都執行相同的代碼時,可以在一個案例中包含多個匹配項。此外,這是一個好主意,包括默認模式,處理不匹配其他任何字符串:
case "$command" in
"my-tweets" | "do-what-it-says")
node liri.js "$command" ;;
"spotify-this-song" | "movie-this")
echo What item would like to query?
read item
node liri.js "$command" "$item" ;;
*)
echo "Unknown command: $command" ;;
esac
至於循環:一般情況下,你要麼使用類似while read command; do
(注意缺乏[ ]
,因爲我們使用的是read
命令,而不是test
又名[
命令);或者只使用while true; do read ...
,然後檢查循環內部的結束條件和break
。在這裏,最好做後者:
while true; do
echo "What command would like to run?"
read command
case "$command" in
"my-tweets" | "do-what-it-says")
node liri.js "$command" ;;
"spotify-this-song" | "movie-this")
echo What item would like to query?
read item
node liri.js "$command" "$item" ;;
"end")
break ;;
*)
echo "Unknown command: $command" ;;
esac
done
縮進代碼。 – Cyrus
請看看:http://www.shellcheck.net/ – Cyrus