My bash script's if / then check is always evaluating to true

0

I was trying to write a bash script to handle a conditional switch, and it kept evaluating to true every time. So, I stripped it down to this, and I was getting the same behavior of it always echoing whatever parameter I sent it instead of only when sending it -c:

myfunc(){
if [[ $1 == "-c" ]];
  then
    echo $1
  fi
}

kayleeFrye_onDeck

Posted 2016-03-07T20:54:29.087

Reputation: 183

Answers

0

While I can't answer why this was always evaluating to true, I was able to fix it. I ended up having to remove the quotes from the switch, thus making the working version look like this:

myfunc(){
if [[ $1 == -c ]];
  then
    echo $1
  fi
};

Per Darth Android's suggestion, just keep the quotation marks consistent between the two comparisons, which is safer.

myfunc(){
if [[ "$1" == "-c" ]];
  then
    echo $1
  fi
};

kayleeFrye_onDeck

Posted 2016-03-07T20:54:29.087

Reputation: 183

Did you try "$1" == "-c" ? Removing quotes from variables is usually a setup for a bad time, such as if $1 contains spaces. – Darth Android – 2016-03-07T22:13:23.267

Nope, I did not try that. I like yours, more! :) – kayleeFrye_onDeck – 2016-03-07T22:20:09.517

You may or may not quote the variable inside [[ ]], it doesn't matter (this is unique to the [[ keyword; you should still quote inside [ ] and anywhere else, unless you really know you want not to quote). Quoting the string after == makes a difference if the string contains *, ? and/or such; here the string doesn't. So your two solutions are equivalent. Moreover they are equivalent to the original code in question, at least in theory, according to the specification. In practice the original code works for me in Bash 4.4.12, 4.4.7, 4.3.30, 4.2.28. No idea what happened in your case. – Kamil Maciorowski – 2019-07-17T19:37:49.967