Bash if-else:意外令牌附近的语法错误`else'

时间:2017-05-01 21:13:10

标签: linux bash shell command wget

我正在尝试使用wgetlynx -dump编写一个实现简单Web浏览器的脚本。在尝试询问用户要做什么(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' 

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

2 个答案:

答案 0 :(得分:2)

elif需要then

e.g。

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

答案 1 :(得分:0)

    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