运行非常简单的shell脚本时出现语法错误

时间:2016-01-20 22:29:46

标签: linux shell unix

在运行关于摇滚,纸张和剪刀的小脚本时,我得到了这个错误。这是我的代码,它在第二个elif语句中失败了,你能弄清楚为什么吗?

function compare () {
    if [ "$userChoice" == "$computerChoice" ]
       then echo "Empate!"
    elif [ "$userChoice" == "piedra" ]
        if [ "$computerChoice" == "tijeras" ]
            then echo "La piedra gana"
        else
            echo "El papel gana"
        fi
    elif [ "$userChoice" == "papel" ]
        if [ "$computerChoice" == "piedra" ]
            then echo "El papel gana"
        else
            echo "Las tijeras ganan"
        fi
    fi
}
compare $userChoice $computerChoice

错误消息是:

myscript: line 10: syntax error near unexpected token `elif'
myscript: line 10: `    elif [ "$userChoice" == "papel" ]'

2 个答案:

答案 0 :(得分:0)

在elif之后你也需要then

答案 1 :(得分:0)

你忘记了一对夫妇"然后"声明。永远记住的好方法是添加"然后"声明与" if"在同一行。示例如下。

function compare () {
if [ "$userChoice" == "$computerChoice" ] ; then
  echo "Empate!"
elif [ "$userChoice" == "piedra" ] ; then
  if [ "$computerChoice" == "tijeras" ] ; then
     echo "La piedra gana"
  else
     echo "El papel gana"
  fi
elif [ "$userChoice" == "papel" ] ; then
  if [ "$computerChoice" == "piedra" ] ; then
     echo "El papel gana"
  else
      echo "Las tijeras ganan"
  fi
fi
}
compare $userChoice $computerChoice