我试图找到我的两个文件的差异,但无法让它产生任何东西。这是我所做的
#Compare files and redirect output
ACTUAL_DIFF=`diff file.current file.previous 2>/dev/null`
if [ $? -ne 0 ]
then
echo "Comparing /tmp/file.current state (<) to /tmp/file.previous state (>), difference is: "
echo ""
echo $ACTUAL_DIFF | cut -f2,3 -d" "
echo ""
else
echo "The current file state is identical to the previous run (on `ls -l file.previous | cut -f6,7,8 -d" "`) OR this is the initial run!"
echo ""
cat /tmp/file.diff
echo ""
fi
答案1
您需要将变量放在引号中,否则换行符将被视为单词分隔符,并且所有输出都将在一行上:
echo "$ACTUAL_DIFF" | cut -f2,3 -d" "
另一种方法是不使用变量,直接通过管道传递diff
到cut
:
diff file.current file.previous 2>/dev/null | cut -f2,3 -d" "
您可以cmp
在开始时使用更简单的命令来测试文件是否不同。
要将输出放入文件中并显示它,请使用该tee
命令。
#Compare files and redirect output
ACTUAL_DIFF=`diff file.current file.previous 2>/dev/null`
if ! cmp -s file.current file.previous 2>/dev/null
then
echo "Comparing /tmp/file.current state (<) to /tmp/file.previous state (>), difference is: "
echo ""
diff file.current file.previous 2>/dev/null | cut -f2,3 -d" " | tee /tmp/file.diff
echo ""
else
echo "The current file state is identical to the previous run (on `ls -l file.previous | cut -f6,7,8 -d" "`) OR this is the initial run!"
echo ""
cat /tmp/file.diff
echo ""
fi