【问题标题】:Bash if-else: Syntax error near unexpected token `else'Bash if-else:意外标记“else”附近的语法错误
【发布时间】:2017-05-01 21:13:10
【问题描述】:

我正在尝试编写一个使用wgetlynx -dump 实现简单网络浏览器的脚本。在尝试询问用户该怎么做(b 返回或q 退出)时,我遇到了语法错误:

#!/bin/bash
echo "Welcome, please do one of the options:
Type an URL
or press b to go BACK to the previuse URL
or press q to QUIT "

read x

if [[ $x = "q" ]]
then
  exit
elif [[ $x = "b" ]]
tail -n urls.txt | wget
else
  $x >> urls.txt
  wget $x
fi

这是我运行 ./browser 并尝试输入 q 时得到的结果:

$ ./browser
Welcome, please do one of the options:
Type an URL
or press b to go BACK to the previuse URL
or press q to QUIT
q
./browser: line 14: syntax error near unexpected token `else'
./browser: line 14: `else' 

我希望它只接受命令并退出而不会出错。

【问题讨论】:

  • 如果您想获得更多答案,您应该在此处添加代码和错误消息。使用edit 和代码格式。截图不是提问的正确方式。在help center 中了解更多信息。
  • 粘贴代码而不是使用屏幕截图并明确包含您的错误消息。
  • 欢迎来到stackoverflow!我用您在屏幕截图中的代码、实际输出(您收到的错误消息)和预期输出(您想要发生的情况)更新了您的问题。这通常是一种很好的提问方式,可以应用于下一个问题! :)
  • 另一种方法是使用case $x in ....

标签: linux bash shell command wget


【解决方案1】:

elif 需要then

例如

  if false
  then
      echo in if
  elif true
  then
      echo in elif
  fi

【讨论】:

    【解决方案2】:
        read x
    
        if [[ $x = "q" ]]
        then
          exit
        elif [[ $x = "b" ]]
        then                    //you missed "then" here
        tail -n urls.txt | wget
        else
          $x >> urls.txt
          wget $x
        fi
    

    【讨论】:

    • 虽然欢迎使用此代码 sn-p,并且可能会提供一些帮助,但它会是 greatly improved if it included an explanation of 如何解决这个问题。没有这个,你的回答就没有多少教育价值了——记住你是在为未来的读者回答这个问题,而不仅仅是现在提问的人!请edit您的答案添加解释,并说明适用的限制和假设。
    猜你喜欢
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 2018-12-18
    • 2014-01-20
    • 2015-12-11
    • 2021-07-29
    相关资源
    最近更新 更多