shell脚本中的条件不起作用

时间:2014-04-06 10:37:25

标签: linux shell unix

我的shell程序是:

  testname=methun
  echo "Please enter your name:"
  read username
  if [ "$username" == "$testname"]; then
   age=20
   echo " you are $age years old."
  else
    echo "How old are you?"
    read Age
    if [ "$Age" -le 20]; then
      echo "you are too young."
   else
    if["$Age" -ge 100]; then
      echo " You are old."
    else 
      echo "you are young."
  fi  fi fi

现在,当我运行程序时,它可以接受用户输入并显示错误。 错误如下:

./filename line linenumber:sysntax error near unexpected token 'then'
./filename line linenumber: 'if["$username" -eq "$testname"]; then'

3 个答案:

答案 0 :(得分:1)

您在括号内缺少一些空格。它必须是这样的:

if [ "$username" -eq "$testname" ]; then

然后你会发现你有第二个问题,-eq是数字,而不是字符串。所以:

if [ "$username" = "$testname" ]; then

答案 1 :(得分:1)

你遗漏了一些空格:

#!/bin/bash
testname=methun
echo "Please enter your name:"
read username

if [ "$username" == "$testname" ]; then
  age=20
  echo " you are $age years old."
else
  echo "How old are you?"
  read Age
  if [ "$Age" -le 20 ]; then
    echo "you are too young."
  else
    if [ "$Age" -ge 100 ]; then
      echo " You are old."
    else
      echo "you are young."
    fi
  fi
fi

答案 2 :(得分:0)

您需要添加一些空格:

if [ "$username" == "$testname" ] ; then
                               ^
                               |
                             here

否则要比较的字符串将是$testname加上]的值。然后]将丢失,因此语法错误。

脚本中的每个if都是如此。

];之间的空格并非严格需要,但无论如何我都喜欢它。