Io-Redirection

顯示文件差異的腳本

  • March 1, 2017

我試圖找出我的 2 個文件的不同之處,但無法讓它產生任何東西。這是我所做的

#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

您需要將變數放在引號中,否則換行符將被視為單詞分隔符,並且所有輸出都將在一行上:

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

引用自:https://unix.stackexchange.com/questions/348481