Jerrybibo
Jerrybibo

Reputation: 1325

While loop in BASH script causing syntax error

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!

Upvotes: 0

Views: 630

Answers (2)

Jerrybibo
Jerrybibo

Reputation: 1325

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

Upvotes: 1

Walter A
Walter A

Reputation: 20012

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

Upvotes: 1

Related Questions