Bash:意外令牌附近的语法错误`then'

时间:2014-02-10 07:31:47

标签: linux bash if-statement

错误发生在第21行......

if [ $weight1 -gt $weight2 ];
    then echo "Weight 2 should be greater than Weight 1."
else
    if [ $weight1 -ge 20 ] && [ $weight1 -le 39 ];
        then echo "Weight 1 is bike."
    else 
        echo "Weight 1 is either bicycle, car, van or lorry."
    fi
fi

2 个答案:

答案 0 :(得分:5)

我没有看到问题,在我的测试then关键字适用于您的情况,无论如何在您的代码中注明了一些:

  1. then放在if运营商的行上:

    if [ $weight1 -ge 20 ] && [ $weight1 -le 39 ]; then
    
  2. 将变量括在引号中:

    if [ "$weight1" -ge 20 ] && [ "$weight1" -le 39 ]; then
    
  3. 我建议使用-a密钥,而不是两次拨打[ app:

    if [ "$weight1" -ge 20 -a "$weight1" -le 39 ]; then
    
  4. 注意:错误Syntax error near unexpected token 'then'可能会在少数情况下上升:

    1. then案例之外指定if关键字时:

      weight1=21
          then echo "Weight 1 is bike."
      else
          echo "Weight 1 is either bicycle, car, van or lorry."
      fi
      
    2. 两次指定then时:

      if [ "$weight1" -ge 20 -a "$weight1" -le 39 ]; then
      then echo "Weight 1 is bike."
      
    3. 当您将then置于不正确的位置时,例如,在else运算符之后:

      else
      then
          echo "Weight 1 is either bicycle, car, van or lorry."
      fi
      

答案 1 :(得分:0)

只是

chmod +x test.sh

第一行:     添加#!/bin/bash

然后做:

./test.sh

它正在解决问题