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
}
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
};
  • 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 Mar 7 '16 at 22:13
  • Nope, I did not try that. I like yours, more! :) – kayleeFrye_onDeck Mar 7 '16 at 22:20
  • 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 Jul 17 at 19:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.