Bash : how to squeeze these 2 if statements into one

做~自己de王妃 提交于 2019-12-24 04:26:10

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/28017143/bash-how-to-squeeze-these-2-if-statements-into-one

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!