使用 Ubuntu 20.04.4 LTS (Focal Fossa) diff
(GNU diffutils) 3.7
从这里我们有:
diff a b && echo "no difference" || echo "differences!" ;
如果diff a b
退出代码为 0,则换句话说,我们有一个匹配(一切正常,成功,相同的输入,ab 之间没有区别)。
如何捕获文本“ ”的 diff 结果no difference
并在脚本中稍后使用它?如何重用结果“ no difference
”?
重复使用结果,如屏幕消息:
no difference
diff ab = " "的结果
或者
Same inputs. Match. All ok. No difference. Success.
diff ab = " "的结果
答案1
简短回答
如果您想快速确认文件是否匹配,请使用选项-s
,
diff -s file1 file2
较长的答案
我假设你想学习如何创建 shellscript,所以我建议你从下面的开始,
#!/bin/bash
if ! test -f "$1" || ! test -f "$2"
then
echo "
Usage $0 <file1> <file2>
to check if <file2> and <file2> differ
and do some more operations"
exit 1
fi
diff "$1" "$2"
if [ $? -eq 0 ] # testing exit status ( 0 <--> match )
then
match=true
else
match=false
fi
# maybe several other commands here ...
if $match
then
echo "Same inputs. Match. All ok. No difference. Success. "
else
echo "The files are different"
fi
稍后你可以开始修改它(使其更简单或更复杂)
答案2
使用 sudodus 提供的答案...并略作修改。
两个脚本都可以运行,上面的#1 由 sudodus 编写,下面的#2 由 sudodus 编写。
在下面的脚本#2中,以 结尾的行;
是否 ;
要被删除?
背景
src1 是源目录 = /media/u3/usb2_drive
dest 是目标目录 = /media/u3/d_driveHDD/test
下面的脚本在第 26 部分,因此 match26
if [ $? -eq 0 ] ; # testing exit status ( 0 <--> match ) No differences echo $? = exit code = 0 ;
then
match26=true ;
else
match26=false ;
fi ;
if $match26 ;
then
tput setaf 12 ; echo "diff -rq S D =" |tr '\n' ' ' ;
tput sgr0 ; echo "Match. Same inputs. All ok. No difference. Success. " ;
else
echo "Differences were found. ________________________________________ dirs differ" ;
fi ;```