0

I have a script I am trying to work out to scan my LAN and send me notification if there is a new MAC address that does not appear in my master list. I believe my variables may be messed up. This is what I have:

#!/bin/bash

LIST=$HOME/maclist.log
MASTERFILE=$HOME/master
FILEDIFF="$(diff $LIST $MASTERFILE)"

# backup the maclist first
if [ -f $LIST ]; then
       cp $LIST maclist_`date +%Y%m%H%M`.log.bk
else
        touch $LIST
fi 

# this will scan the network and extract the IP and MAC address
nmap -n -sP 192.168.122.0/24 | awk '/^Nmap scan/{IP=$5};/^MAC/{print IP,$3};{next}' > $LIST

# this will use a diff command to compare the maclist created above and master list of known good devices on the LAN
if [ $FILEDIFF ] 2> /dev/null; then
        echo
        echo "---- All is well on `date` ----" >> macscan.log
        echo
else
       # echo -e "\nWARNING!!" | `mutt -e 'my_hdr From:[email protected]' -s "WARNIG!! NEW DEVICE ON THE LAN" -i maclist.log [email protected]`
        echo "emailing you"
fi

When I execute this when the maclist.log does not exist I get this response:

diff: /root/maclist.log: No such file or directory

If I execute it again with the maclist.log file existing the file gets renamed from the cp line without any issue.

5
  • What is your question? Commented Sep 23, 2016 at 17:45
  • 1
    Why don't you just execute FILEDIFF="$(diff $LIST $MASTERFILE)" after your first conditional block (if [ -f $LIST ] ...) ? Commented Sep 23, 2016 at 17:45
  • @ThomasWilmotte So I tried that and I get no error but the FILEDIFF variable still does not work because I get that email. Or, there could be something wrong with my if [ $FILEDIFF ] statement. Commented Sep 23, 2016 at 17:52
  • @t3kg33k FILEDIFF=diff ... will be an empty string if diff didn't find any difference between the files. You can then check if FILEDIFF is an empty string or not with if [[ "$diff" == "" ]];then ... Commented Sep 23, 2016 at 18:06
  • @ThomasWilmotte Ah! Okay. That makes sense now. And that worked. Thanks! Now, how do I promote your answer as the correct answer? :) Commented Sep 23, 2016 at 18:18

1 Answer 1

1

The line

FILEDIFF="$(diff $LIST $MASTERFILE)"

executes the diff when it is run (not when you use $FILELIST later). At that time the list file hasn't been created.

The easiest fix is just to put the diff command in full where $FILELIST is currently used.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.