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