jonny b
jonny b

Reputation: 75

Saving Mac address in variable in a bash Script and using it to check for changes

I am trying to create a bash script.

  1. The script asks the user for an IP address
  2. The script then greps the arp -a command for the line that the IP address is on.
  3. The MAC address is saved as a variable called MAC.
  4. The script checks that the MAC address has not changed.
#!/bin/bash
# Xdetect

echo "Welcome to Xdetect"
echo "Enter IP address of device to monitor (usually default gateway)"
read IP  

MAC=arp -a | grep $IP | awk {'print $4'}
echo =$MAC
while : 'arp -a | grep $IP | awk {'print $4'}' = $MAC

do
echo "Mac has not changed"
 sleep 2
done

The script does not work, it loops and echoes MAC has not changed even when the mac address changes.

Just before it loops an error appears saying: Xdetect.sh 9: Xdetect.sh: -a: not found

How can I fix this?

Upvotes: 0

Views: 1894

Answers (1)

Jens
Jens

Reputation: 72649

Did you mean test instead of the null command : in your while statement? Something like this, without the anti-pattern grep|awk:

MAC=$(arp -a | awk -v ip="$IP" '$2 == "("ip")" { print $4 }')
echo "$MAC"
while test $(arp -a | awk -v ip="$IP" '$2 == "("ip")" { print $4 }') = "$MAC"; do
   echo "Mac has not changed"
   sleep 2
done

Your observation that the message "Mac has not changed" is printed repeatedly is because : is a null-command always returning true and ignoring (only expanding) its arguments. Effectively your code does

while true; do
   echo echo "Mac has not changed"
   sleep 2
done

Upvotes: 2

Related Questions