簡體   English   中英

Bash循環來比較文件

[英]Bash loop to compare files

我顯然遺漏了一些簡單的東西,並且知道問題是它正在創建一個空白輸出,這就是它無法比較的原因。 但是,如果有人能夠對此有所了解,那就太棒了 - 我沒有把它隔離開來。

最后,我試圖將存儲在txt文件中的列表中的md5sum與存儲在服務器上的列表進行比較。 如果有錯誤,我需要它報告。 這是輸出:

root@vps [~/testinggrounds]# cat md5.txt | while read a b; do
>   md5sum "$b" | read c d
>   if [ "$a" != "$c" ] ; then
>     echo "md5 of file $b does not match"
>   fi
> done
md5 of file file1 does not match
md5 of file file2 does not match

root@vps [~/testinggrounds]# md5sum file*
2a53da1a6fbfc0bafdd96b0a2ea29515  file1
bcb35cddc47f3df844ff26e9e2167c96  file2

root@vps [~/testinggrounds]# cat md5.txt
2a53da1a6fbfc0bafdd96b0a2ea29515  file1
bcb35cddc47f3df844ff26e9e2167c96  file2

不是直接回答你的問題,而是md5sum(1)

-c, --check
read MD5 sums from the FILEs and check them

喜歡:

$ ls
1.txt  2.txt  md5.txt
$ cat md5.txt
d3b07384d113edec49eaa6238ad5ff00  1.txt
c157a79031e1c40f85931829bc5fc552  2.txt
$ md5sum -c md5.txt
1.txt: OK
2.txt: OK

您遇到的問題是您的內部讀取是在子shell中執行的。 在bash中,管道命令時會創建子shell。 子shell退出后,變量$ c和$ d消失了。 您可以使用進程替換來避免子shell:

while read -r -u3 sum filename; do
   read -r cursum _ < <(md5sum "$filename")
   if [[ $sum != $cursum ]]; then
      printf 'md5 of file %s does not match\n' "$filename"
   fi
done 3<md5.txt

重定向3<md5.txt導致文件作為文件描述符3打開。- -u 3 read選項使其從該文件描述符中讀取。 內部read仍然從stdin讀取。

我不打算爭辯。 我只是盡量避免從內部循環中讀取雙重內容。

#! /bin/bash

cat md5.txt | while read sum file
do
    prev_sum=$(md5sum $file | awk '{print $1}')
    if [ "$sum" != "$prev_sum" ]
    then
        echo "md5 of file $file does not match"
    else
        echo "$file is fine"
    fi
done

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM