Need Multiple checks inside if condition in a bash shell script

Hi,

I need to perform the untar and rm operation if the file found is a .tar and does not have test.tar or hello.tar as the file names.

Below is the loop to check the same.

        for tf in *.tar
        do      if [[ ( -f "$tf" ) && ( "$tf" != test.tar || "$tf" != hello.tar ) ]]
                then    found=1
                        echo "UNTAR THIS:"$tf
                        tar xvf "$tf" && rm -rf "$tf"
                        ec=$?
                        if [ $ec -ne 0 ]
                        then    exit $ec
                        fi
                else
                echo "DONT TOUCH THIS TAR:"$tf
                fi
        done

However, when I run the script in debug mode it is only checking the condition "$tf" != test.tar and ignores this check "$tf" != hello.tar

So it untars and removes hello.tar when it was suppose to ignore it.

Can you please suggest.

The problem is with the || . Basically it will stop testing if

"$tf" != test.tar

What you should have had was either of the lines below:

if [[ ( -f "$tf" ) && ( "$tf" != test.tar && "$tf" != hello.tar ) ]]
if [[ ( -f "$tf" ) && !( "$tf" = test.tar || "$tf" = hello.tar ) ]]

In the first case you are asking 'Does "$tf "not match "test.tar" AND does "$tf" not match "hello.tar"?'
In the second case you negate the actual match of $tf to either one or the other.

Andrew

1 Like