how to compare same file and send mail in linux

659 views Asked by At

I am creating bash script on a file to send diff over the mail.

for below case, I have created two files as "xyz.conf" and "xyz.conf_bkp" to compare So far, I have come with below script -

file="/a/b/c/xyz.conf"

while true
do
     sleep 1
     cmp -s $file ${file}_bkp
        if [ $? > 0 ]; then
            diff $file ${file}_bkp > compare.log
            mailx -s "file compare" [email protected] < compare.log
            sleep 2
            cp $file ${file}_bkp
            exit
        fi
done

I have scheduled above script to run every second

* * * * 0-5 script.sh

This is working fine but I am looking with different approach like below - I am looking for to work without creating another backup file Imagine if I have to work multiple files which will lead me to crate those many backups which doesn't look good solution.

Can anyone suggest, how to implement this approach?

1

There are 1 answers

5
chepner On

I would write it this way.

while cmp "$file" "${file}_bkp"; do
  sleep 2
done
diff "$file" "${file}_bkp" | mailx -s "file compare" [email protected]
cp "$file" "${file}_bkp"

I wanted to avoid running both cmp and diff, but I'm not sure that is possible without a temporary file or pipe to hold the data from diff until you determine if mailx should run.

while diff "$file" "${file}_bkp"; do
  sleep 2
done | {
  mailx -s "file compare" [email protected]
  cp "$file" "${file}_bkp"
  exit
}

diff will produce no output when its exit status is 0, so when it finally has a non-zero exit status its output is piped (as the output of the while loop) to the compound command that runs mailx and cp. Technically, both mailx and cp can both read from the pipe, but mailx will exhaust all the data before cp runs, and this cp command would ignore its standard input anyway.