user1335175
user1335175

Reputation: 189

Bash : how to squeeze these 2 if statements into one

I am new to Bash and scripting and I want to figure out a way to combine these two statements into 1 . what this script does is checks if two files D1 and D2 are the same file and if not checks if their content is the same.

if [ ! $D1 -ef $D2 ]

 then
    echo not the same file
        if  cmp -s $D1 $D2  

           then
            echo same info
           else
                echo not same info
        fi

    else
            echo same file


fi

In addition to this, I am also confused when to use [] and when to skip them, manual says when its a conditional use [], but what does that mean ?

Thank you.

Upvotes: 2

Views: 120

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 80992

The syntax of an if statement is (from 2.10 Shell Grammar):

if_clause        : If compound_list Then compound_list else_part Fi
                 | If compound_list Then compound_list           Fi

Where compound_list eventually gets down to a command.

! $D1 -ef $D2 is not a command.

[ is a a command (also known as test). See the output from type [ or type test as well as which [ and which test.

So [ ! $D1 -ef $D2 ] is a valid command used in the if statement.

The return value of the compound_list is what if tests.

So when you are using something like cmp (or any other command) then there is no reason to use [ and, in fact, using [ is incorrect.

As the compound_list can be more than a single command to combine [ ! $D1 -ef $D2 ] and cmp -s $D1 $D2 simply use && as normal. (Need ! on the cmp call too to invert that to get the "not same" test from both.)

if [ ! "$D1" -ef "$D2" ] && ! cmp -s "$D1" "$D2"; then
    echo 'Not same file or same contents'
fi

Upvotes: 1

Related Questions