开发者

shell programming - help automating file comparisons and email any changes

Can someone help me with my shell script? I can't figure out what I'm doin开发者_Go百科g wrong. I stripped this down as best as I could. I'm missing something here with this logic.

My process is fairly simple, but apparently, I'm not coding this properly.

Here is basically what I want to do:

1. get a list (curr.lst) of directories from remote host
2. perform a `diff` on list of directories with (curr.lst) and a previous list (before.lst)
3. if there is a diff (i'm checking this by doing a `du -b` for file size) = 0 bytes, then nothing 
to report
4. if the diff is greater than 0 bytes, then email me the diff

That's it. Here's how I tested it:

1. run the script once
2. edit the before.lst and add/change records to get a diff
3. run again.

My output:

$ ./tst.sh
The file size is:0 bytes   **there should be a diff because I just edited the file
No diff found

Run it again:

$ ./tst.sh 
The file size is:83 bytes  **now it found the diff, but when I do an ls my diff.out is 0 bytes, thus I have nothing to mail
Could not exit
Detected a change
Null message body; hope that's ok

My code:

#!/usr/local/bin/bash

TEST=/dump/stage/procs
BASE=/home/foobar/dev/mon
KEYFILE=/home/foobar/.ssh/mytestfeed-identity

BEFORE="$BASE/before.lst"
CURR="$BASE/curr.lst"
DIFFOUT="diff.out"
MAIL_RECIP="myname@foobar-inc.com"
SIZE=$(du -b "$BASE/$DIFFOUT" | cut -f 1)
ssh -i $KEYFILE user@host ls "$TEST" | perl -nle 'print $1 if m|$TEST/(\S+)|' > "$CURR" 
diff -b -i $BEFORE $CURR > $BASE/$DIFFOUT 2>&1 
echo "The file size is:$SIZE bytes"       2>&1

if [  "$SIZE" = "0" ]; then
    echo "No diff found" 2>&1
    mv $CURR $BEFORE
    exit
else
    echo "Could not exit" 2>&1
fi

if [  "$SIZE" -gt 0 ]; then
        echo "Detected a change" 2>&1
        mailx -s "Changes detected in $TEST dirs" $MAIL_RECIP < $BASE/$DIFFOUT
        mv $CURR $BEFORE 
fi


You are executing the size calculation (du -b "$BASE/$DIFFOUT") before you run the diff. That means that you get the size of $DIFFOUT generated during the last run of the script. The $DIFFOUT of the current run has a size of 0 because you moved $CURR to $BEFORE during the last script run.

I think you should simply move the du line after the diff line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜