2

My shell program is:

  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

Now when I run my program, it's able to take user input and it shows an error. The error is given below:

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

3 Answers 3

1

You are missing some whitespaces:

#!/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
Sign up to request clarification or add additional context in comments.

1 Comment

I rechecked, to be really sure and no, that code does execute without an error.
1

You are missing some spaces inside your brackets. It needs to be like this:

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

Then you will realize you have a second problem, which is -eq is for numbers, not strings. So:

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

Comments

0

You need to add a few whitespaces:

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

Or else the string to compare to will be the value of $testname plus an ]. Then the ] will be missing and thus a syntax error.

The same is true for every if in your script.

The space between ] and ; is not strictly needed, but I like it anyway.

2 Comments

== is not POSIX; = is.
@JohnZwinck: Good to know, but I doubt this is related to the OP problems.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.