0

I recently started writing BASH scripts, and I am currently trying to practice using while loops. However, when I run the following block of code, the command prompt responds with:

run.command: line 12: syntax error near unexpected token `done'
run.command: `done'

Then the program shuts off. This is the code I am running.

#!/bin/bash
echo -e "text"
c=false
while true; do
    printf ">> "
    i=read 
    if [$i = "exit"]; then
        exit
    else if [$i = "no"]; then
        echo "no"
    else
        echo -e "Error: $i is undefined"
    fi
done

I did some research on while loops, however my loop syntax seems correct. When I remove the done at the end, and Unexpected end of file error occurs. Any help would be appreciated!

1
  • 2
    Please take a look: shellcheck.net Commented Jan 27, 2016 at 17:29

2 Answers 2

1

You can use the -p option of read for the prompt and a case ... esac construction:

while true; do
  read -r -p ">> " i
  case "$i" in
     "exit") exit 0  ;;
     "no") echo "no" ;;
     *) echo -e "Error: $i is undefined";;
  esac
done
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I'll do more research on this.
1

I fixed it myself!

#!/bin/bash
echo -e "text"
c=false
while true; do
  printf ">> "
  read i
  if [ "$i" = "exit" ]; then
    exit
  elif [ "$i" = "no" ]; then
     echo "no"
  else
     echo -e "Error: $i is undefined"
  fi
done

6 Comments

You should quote $i, to avoid a "too many arguments" error from [.
Explanation: Test it with an input with two or more words. You can use "$i"
Thanks for the tip! Is there any more things I can improve upon?
@Jerrybibo, using echo -e is actually best avoided: Supporting that option to do anything other than print -e on output is contrary to the POSIX spec for echo. If you want format string support, use printf.
@Jerrybibo, ...see pubs.opengroup.org/onlinepubs/009604599/utilities/echo.html for the aforementioned specification (and note all the caveats: Behavior when given a string with any backslash is undefined in POSIX echo; behavior when given -n is undefined; behavior when given -e is defined, but defined in such a way as to require -e to be printed on output; etc).
|

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.