Bash loop to compare files

I obviously missed something, and I know that the problem is that it creates an empty output, so it cannot compare. However, if someone could shed light on this, it would be great - I did not isolate him.

Ultimately, I am trying to compare md5sum with a list stored in a txt file, with that stored on the server. If errors, I need to report it. Here's the conclusion:

 root@vps [~/testinggrounds]# cat md5.txt | while read ab; do > md5sum "$b" | read cd > 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 
+4
source share
3 answers

I will not argue. I just try to avoid double reading from inner loops.

 #! /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 
+3
source

Directly answering your question, but md5sum (1) :

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

how

 $ 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 
+7
source

The problem you are facing is that your internal reading is done in a subshell. In bash, when working with a command, a subshell is created. As soon as the subshell exits, the variables $ c and $ d disappear. You can use process overriding to avoid a subshell:

 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 

Redirecting 3<md5.txt causes the file to open as a file descriptor 3. The -u 3 option to read causes it to read from this file descriptor. The internal read is still being read from stdin.

+4
source

Source: https://habr.com/ru/post/1233392/


All Articles