我是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
除此之外,我也很困惑何时使用[]以及何时跳过它们,手动说当它有条件使用[],但这是什么意思?
谢谢。
答案 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