1

I'm trying to have the script exit if the user enters 'q'

here's the code:

echo "Enter Choice => "
    read target
if [[ $target=='q' ]]; then
  exit 1
else
  #do something
fi

However when I run it no matter what the input is, the script exits...

Magnus Melwin
  • 1,509
  • 1
  • 21
  • 32
llssff
  • 119
  • 7
  • It's checking whether `"$target==q"` is a non-empty string. It's always non-empty, because no matter what `$target` is, `==q` is non-empty itself. – Charles Duffy Mar 17 '19 at 04:52
  • You need spaces -- `[[ $target = q ]]` -- if you want to compare against `q`. (`=` is preferred because it's valid in POSIX `test`, whereas `==` is a nonportable extension). – Charles Duffy Mar 17 '19 at 04:52
  • BTW, if you pasted your code into http://shellcheck.net/, it would link you to [SC2077](https://github.com/koalaman/shellcheck/wiki/SC2077), a page describing this error. – Charles Duffy Mar 17 '19 at 04:55

1 Answers1

0
#!/bin/bash
echo "Enter Choice => "
    read target
if [[ $target == 'q' ]]; then
  exit 1
else
  #do something
  echo "do something..."
fi

~                            

Try this - spacing between the tokens $target, '==' and 'q' is important.

Magnus Melwin
  • 1,509
  • 1
  • 21
  • 32
  • 1
    See the "Answer Well-Asked Questions" section of [How to Answer](https://stackoverflow.com/help/how-to-answer) in the Help Center, particularly the bullet point regarding questions which *...have already been asked and answered many times before*. – Charles Duffy Mar 17 '19 at 04:53
  • So its not the if loop thats bugging out but the comparison operator? – llssff Mar 17 '19 at 05:20
  • the space between the comparison operator is important. – Magnus Melwin Mar 17 '19 at 05:23