-1

I was making a bash script for my Linux. But I am stuck on if or loop. If I select yes it's spamming ==yes.

 echo "Found a previously saved file. Do you want to continue with this? (Yes/No)"
    read Response
if [["$Response" == "Yes" || "$Response" == "yes" || "$Response" == "y" || "$Response" == "Y"]]; then
    echo "Success" 
    else
    echo "Fail"
    fi
Innat
  • 16,113
  • 6
  • 53
  • 101
Bipul Dey
  • 11
  • 5

1 Answers1

0

You need a space between [[ and " and also between "and ]]. You can also drop " around your strings when using [[ and ]] to test - but leave the space there. Otherwise, bash will do this:

[[yes == Yes

With the response:

[[yes: command not found...

The || makes it try the next part and it's here that it executes the command that becomes the "magical" loop:

yes == yes

yes is actually a command that will repeat what you give it as an argument (it defaults to y to be able to do yes | program to answer all questions that program asks with y). It will continue to repeat the same thing until stdout is closed (the receiver closes stdin).

So, it will print == yes in an endless stream.

Fix:

#!/bin/bash

echo "Found a previously saved file. Do you want to continue with this? (Yes/No)"
read -r Response

if [[ $Response == Yes || $Response == yes || $Response == y || $Response == Y ]]; then
    echo "Success" 
else
    echo "Fail"
fi
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • May be the double quote marks are not necessary here, but sometimes it happens the parameter is empty – then `$x = yes` may become ` = y` which is not a valid expression. – CiaPan May 11 '21 at 12:50
  • 1
    @CiaPan No, not with `[[` / `]]` - You're thinking of `[` / `]`. Try it: `if [[ $empty1 == $empty2 ]]; then` (where both are empty or even undefined). – Ted Lyngmo May 11 '21 at 12:50
  • 1
    Thanks, @Ted ! You made me realize I have lived a good part of my life in error. Luckily, with no bad consequences! :D – CiaPan May 11 '21 at 12:57
  • Of course, a `case` statement would be a lot more elegant and idiomatic here. – tripleee May 11 '21 at 13:09
  • @tripleee Yes, or chepner's suggestion. `[[ $Response = [yY]?(es) ]]` is pretty nice too. – Ted Lyngmo May 11 '21 at 13:48