Pergunta

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?

Foi útil?

Solução

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).

Outras dicas

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top