Bash:如何将这两个if语句压缩成一个

时间:2015-01-19 02:29:34

标签: bash scripting

我是Bash和脚本的新手,我想找到一种方法将这两个语句合并为1。这个脚本的作用是检查两个文件D1和D2是否是同一个文件,如果不是,则检查它们的内容是否相同。

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

除此之外,我也很困惑何时使用[]以及何时跳过它们,手动说当它有条件使用[],但这是什么意思?

谢谢。

1 个答案:

答案 0 :(得分:1)

if语句的语法是(来自2.10 Shell Grammar):

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

compound_list最终归结为命令。

! $D1 -ef $D2不是命令。

[是一个命令(也称为test)。请参阅type [type test以及which [which test的输出。

因此[ ! $D1 -ef $D2 ]if语句中使用的有效命令。

compound_list的返回值是if测试的内容。

因此,当您使用cmp(或任何其他命令)之类的内容时,没有理由使用[,事实上,使用[是不正确的。

由于compound_list可以只有一个命令来合并[ ! $D1 -ef $D2 ]cmp -s $D1 $D2,所以只需正常使用&&即可。 (!来电时也需要cmp来反转它,以便从两者中获得"不相同的测试。)

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