1

Here is my code:

#!/bin/bash
echo "Letter:"
read a
if [ $a = "a" ]
then
     echo "LOL"
fi
if [ $a = "b" ]
then
      echo "ROFL"
fi

Is there a way for me to loop this so that, after displaying either LOL or ROFL, I would be asked for a letter again?

2 Answers 2

2

Yes.

Oh, you want to know how?

while true; do
  echo "Letter:"
  read a
  if [ $a = "a" ]
  then
     echo "LOL"
  elif [ $a = "b" ]
  then
      echo "ROFL"
  fi
done

Of course, you probably want some way to get out of that infinite loop. The command to run in that case is break. I would write the whole thing like this:

while read -p Letter: a; do 
  case "$a" in
    a) echo LOL;;
    b) echo ROFL;;
    q) break;;
  esac
done

which lets you exit the loop either by entering 'q' or generating end-of-file (control-D).

Sign up to request clarification or add additional context in comments.

Comments

1

Don't forget that you always want -r flag with read.
Also there is a quoting error on that line:

if [ $a = "a" ] # this will fail if a='*'

So here is a bit better version(I've also limited the user to input only 1 character):

#!/bin/bash
while true; do
    read -rn1 -p 'Letter: ' a
    echo
    if [[ $a = 'a' ]]; then
        echo "LOL"
    elif [[ $a = 'b' ]]; then
        echo "ROFL"
    else
        break
    fi
done

Or with switch statement:

#!/bin/bash
while read -rn1 -p 'Letter: ' a; do 
    echo
    case $a in
        a) echo LOL;;
        b) echo ROFL;;
        *) break;;
    esac
done

Comments

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.