11

Trying to write a script which will read what a user has imput... I know it's basic but im stuck on the first if..

echo  "Please enter yes or no (y/n)?"
read string
if [ $string = "y" -o "n" ]
   then
      echo "User selected $string"
   else
      echo "You didn't enter y/n !!!"
fi

I would like it to be if [ $backup = "y" or "n" ]

Any ideas?

bsmoo
  • 949
  • 4
  • 10
  • 23

4 Answers4

13

Use this syntax in bash :

if [ "a string" = "another one" ] ; then

# Whatever

fi

For multiple conditional statements such as OR, use:

if [ "a string" = "another one" ] || [ "$foo" = "bar" ] ; then

# Whatever

fi

bash also supports the non-standard [[ ... ]] expression, which can process a compound comparison using a single command, rather than 2 [ commands:

if [[ "a string" = "another one" || $foo = "bar" ]]; then

# Whatever

fi
chepner
  • 497,756
  • 71
  • 530
  • 681
Halim Qarroum
  • 13,985
  • 4
  • 46
  • 71
4

Not the question you actually asked, but... You told the user to enter "yes" or "no" but only test for y or n - sure, you gave them a hint but users are hint-resistant. So maybe a looser test is in order:

echo "Please enter yes or no (y/n)"
read string
case "$string" in
    [yY]* | [nN]*) echo "User entered $string" ;;
    *) echo "I don't understand '$string'" ;;
esac

That will recognize any variation that begins with Y or N - usually that's good enough, but you could tighten up the tests. Also, since you'll probably want to do something different with a yes or no response you can expand the case (I've also tightened the tests in this one):

case "$string" in
    [yY] | [yY][eE][sS]) echo "Here's where you process yes" ;;
    [nN] | [nN][oO]) echo "And here you deal with no" ;;
    *) echo "I don't understand '$string'" ;;
esac

You could do this with if statements but I find case more readable when more than two alternatives are possible and the test is appropriate to case syntax.

William
  • 4,787
  • 2
  • 15
  • 14
3

You can also try:

echo  "Please enter yes or no (y/n)?"
read string
if [[ "$string" =~ ^(y|n)$ ]]
   then
      echo "User selected $string"
   else
      echo "You didn't enter y/n !!!"
fi
Joao Morais
  • 1,885
  • 13
  • 20
0

I nice solution is would be with case, which is easier to extend if you want to make your input more complex

case $string in
  y|n) echo "User selected $string"
      ;;
  *) echo "You didn't enter y/n !!!"
      ;;  
esac

From there you can easily modify it to accept Uppercase or whatever:

case $string in
  y|Y) echo "yes, Sir!"
      ;;
  n|N) echo "No, can't do"
      ;;
  *) echo "Say what?"
      ;;  
esac

Check case statements for more info.

Chirlo
  • 5,989
  • 1
  • 29
  • 45