Bash – Logical AND in a bash script

bashshell-script

I have an if in my bash script that has to check if EITHER of the 2 files exists, if they don't exist it should echo match.

Code I have:

if [[ ! -f /etc/benchmarking/code ]] && [[ ! -f /etc/benchmarking/code.class ]]; then
 echo "match"
fi

But this doesn't not seem to work for some reason.

I am 110% sure that these 2 files do not exist. I don't get any errors, it just doesn't enter the if.

I am new to bash scripting so I'm not sure what could be wrong.

Best Answer

If you want either then you want OR, not AND.

if [[ ! -f /etc/benchmarking/code ]] || [[ ! -f /etc/benchmarking/code.class ]]; then
 echo "match"
fi
  • This will match if either or both files are missing.
  • Your code will only print match if both do not exist.

But, you said:

I am 110% sure that these 2 files do not exist. I don't get any errors, it just doesn't enter the if.

So your statement contradicts itself. At least one of those files must exist, if you are running that code.

If you want to see how your if statement is evaluating, run it with -x.

#!/bin/bash -x
if [[ ! -f /etc/benchmarking/code ]] && [[ ! -f /etc/benchmarking/code.class ]]; then
 echo "match"
fi

Then you'll see the execution.

$ ./test.sh
+ [[ ! -f /etc/benchmarking/code ]]
+ [[ ! -f /etc/benchmarking/code.class ]]
+ echo match
match
$ 
Related Question