Bash:如何将这两个if语句压缩为一个 [英] Bash : how to squeeze these 2 if statements into one
问题描述
我是Bash和脚本编写的新手,我想找出一种将这两个语句合并为1的方法.该脚本的作用是检查两个文件D1和D2是否是同一文件,如果不是,则检查它们的内容是否相同.
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 ?
谢谢.
推荐答案
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
compound_list
最终归结为命令的地方.
Where compound_list
eventually gets down to a command.
!$ D1 -ef $ D2
不是命令.
[
是一个命令(也称为 test
).查看 type [
或 type test
的输出,以及哪个[
和哪个测试
.
[
is a a command (also known as test
). See the output from type [
or type test
as well as which [
and which test
.
所以 [!$ D1 -ef $ D2]
是 if
语句中使用的有效命令.
So [ ! $D1 -ef $D2 ]
is a valid command used in the if
statement.
compound_list
的返回值是 if
测试的内容.
The return value of the compound_list
is what if
tests.
因此,当您使用诸如 cmp
之类的命令(或任何其他命令)时,就没有理由使用 [
,实际上,也使用了 [
不正确.
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.
由于 compound_list
可以不仅仅是将 [!$ D1 -ef $ D2]
和 cmp -s $ D1 $ D2
只需正常使用&&
即可.(也需要在 cmp
调用上使用!
来将其求反以从两者中获得不相同"的测试.)
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
这篇关于Bash:如何将这两个if语句压缩为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!