-2

I have a code bit like this which works just fine;

if [ "$1" == "something1" ] || [ "$1" == "something2" ] || [ "$1" == "something3" ]; then
    echo "Result is $1"
    # do stuff here if $1 is not equals to one of the above "somethings"
fi
$ ./script.sh something2
Result is something2

However, when I change the equal operators (==) into not equals (!=) then it simply doesn't work anymore.

Example:

if [ "$1" != "something1" ] || [ "$1" != "something2" ] || [ "$1" != "something3" ]; then
    echo "Result is $1"
    # do stuff here if $1 is not equals to one of the above "somethings"
fi
$ ./script.sh something2
Result is something2

It shouldn't have print out the Result is something2. I added this to my bash script #!/bin/bash -x to see the problem and it says + [[ something2 != something1 ]] when I run the script as ./script.sh something2 so definitely something's wrong here.

I basically want it to continue the if statement if the $1 is not equals to one of the somethings otherwise skip.

What am I missing?

Marry Jane
  • 305
  • 2
  • 15
  • Generally with the reverse you want to use AND instead of OR. If you read your current line, it reads _if `$1` is not "something1" or `$1` is not "something2"_. Now imagine `$1` equals "something2" then _$1 is not "something1"_ is by default true. So the condition you write will always be true. You should convert your `||` into `&&` – kvantour Jan 22 '20 at 11:39
  • check again your input/output and the conditions in each case. Whatever is inside the if block gets executed in both cases input ("something1" , "something2") and with both `==` and `!=` versions. And BTW the output in your second case should be `Result is something2` instead (I tested on my side) – nullPointer Jan 22 '20 at 11:39
  • 1
    [De Morgan's laws](https://en.wikipedia.org/wiki/De_Morgan%27s_laws) – KamilCuk Jan 22 '20 at 11:40
  • 1
    @KamilCuk, a bit heavy on the stomach, but yes – kvantour Jan 22 '20 at 11:42

1 Answers1

2

You can use this.

if [ "$1" != "something1" ] && [ "$1" != "something2" ] && [ "$1" != "something2" ]; then
    echo "Result is $1"
    # do stuff here if $1 is not equals to one of the above "somethings"
fi

Reason is even though one OR condition fails in your example, other OR conditions are true and the commands inside the if is executed.

Thilina Jayanath
  • 198
  • 1
  • 10