0

I'm trying to write a simple bash script that checks the string if value is not "rpm" or "jar". But it seems to always be evaluating to true. I'm not sure what I'm missing.

#!/bin/bash
FILE_EXTENSION="rpm"

if [ "$FILE_EXTENSION" != "jar" ] || [ "$FILE_EXTENSION" != "rpm" ];
then
    echo "File type is NOT rpm or jar";
else
    echo "File type is rpm or jar";
fi

echo "Debug: FILE_EXTENSION value is $FILE_EXTENSION"

Running it on my local gets below output. It evaluates to true even though FILE_EXTENSION variable is set as "rpm"

$ ./check3.sh 
File type is NOT rpm or jar
Debug: FILE_EXTENSION value is rpm
$
Newbie Dev
  • 55
  • 6

2 Answers2

1

You are confused about the logic. a OR b is true if a is true and you don't care about b; and it is true when b is true and then you don't need to care about the value of a. The trivial fix for your problem is to switch to && which is apparently what you wanted to check for.

I would in fact also prefer a case statement, as it is easier on the eyes (once you get past the syntax of the case statement itself, which can be unsettling if you are unfamiliar with it).

case $file_extension in
  rpm | jar) echo "File type is rpm or jar";;
  *) echo "File type is not rpm or jar";;
esac

See also Correct Bash and shell script variable capitalization; I switched to lower case for this reason.

tripleee
  • 175,061
  • 34
  • 275
  • 318
0

That's because you're using or (||) instead of an and (&&). Currently you're checking if:

rpm != jar -> True
rpm != rpm -> False
True or False => True and you get "File type is NOT rpm or jar"
omer.hazan
  • 129
  • 2