3
#!/bin/bash 
until [read command -eq "end"] 
do 
echo What command would like to run? 
read command 
if [$command -eq "my-tweets"]; then 
node liri.js $command 
fi 
if [$command -eq "do-what-it-says"];then 
node liri.js $command 
fi 
if [$command -eq "spotify-this-song"]; then 
echo What item would like to query? 
read item 
node liri.js $command $item 
fi 
if [$command -eq "movie-this"]; then 
echo What item would like to query? 
read item 
node liri.js $command $item 
fi 
done 

我正在試圖創建一個case/if語句,以在運行代碼的下一部分之前檢查變量的值。我想檢查$command的值,以根據用戶輸入的值創建此案例/ if語句。我不斷收到命令找不到錯誤。在bash腳本中寫入case語句

+0

縮進代碼。 – Cyrus

+2

請看看:http://www.shellcheck.net/ – Cyrus

回答

1

括號內需要空格。 []不是shell語言功能,[是一個命令名稱,它需要關閉]參數才能使事物看起來很漂亮([read將搜索命名爲[read的命令(可執行文件或內置命令))。

裏面的字符串比較[]完成=,-eq是用於整數比較。

您應該仔細閱讀dash(1)聯機幫助頁或POSIX shell language specification。他們不是那麼大(Bash更大)。你也可以在這裏找到case語句的語法。

+1

另外,雙引號所有變量引用。 '如果[$ command =「my-tweets」]'如果'$ command'爲空或者包含多個單詞或者......多個其他條件,則會發出錯誤。 'if [「$ command」=「my-tweets」]'會起作用。 –

+1

非常感謝。這真的有幫助。我能夠快速獲得我的代碼來評估命令是否等於設定值並從那裏開始。 –

0

除了語法錯誤@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 
+0

非常感謝。這是一個很好的速成課程,正是我所期待的。代碼現在完美運行。 –

0

在基於參數的bash中簡單使用case。

case "$1" in 
    argument1) 
     function1() 
     ;; 

    argument2) 
     function2() 
     ;; 
    *) 
     defaultFunction() 
     ;; 

esac