-1
IPv4=$( ifconfig |grep -v 'eth1:' |grep -A 1 'eth1'| tail -1 |cut -d ':' -f 2 |cut -d ' ' -f 1)
IPnode1=$"111.22.333.44"
IPnode2=$"111.22.333.45"


ifconfig |grep -v 'eth1:' |grep -A 1 'eth1'| tail -1 |cut -d ':' -f 2 |cut -d ' ' -f 1

if [[ "$IPv4" = "$IPnode1" ]]; then

   echo "found the address "
   echo "111.22.333.44   VM01.com VM01" >> /etc/hosts

else

   echo "The address does not match"

fi

  ifconfig |grep -v 'eth1:' |grep -A 1 'eth1'| tail -1 |cut -d ':' -f 2 |cut -d ' ' -f 1

if [[ "$IPv4" = "$IPnode2" ]]; then


      echo ""
      echo "found the address "
      echo "111.22.333.45   VM02.com VM02" >> /etc/hosts

else

   echo "The address does not match"

fi
melpomene
  • 84,125
  • 8
  • 85
  • 148
  • What's in $IPv4 after executing the first line? – Hellmar Becker Nov 17 '18 at 17:05
  • BTW, `ifconfig` on Linux is deprecated and has been unmaintained (except by distros adding their own local patches) for over a decade; it's completely unaware of modern Linux networking features (like named aliases), and consequently can misrepresent advanced configurations' status. New code should use the `ip` tool from `iproute2` instead; this also gives you a single-line-per-interface output option so you don't need hackery equivalent to the `grep -A 1 | tail` done here. – Charles Duffy Nov 17 '18 at 20:16
  • More to-the-point, `PS4=':$LINENO+' bash -x yourscript` will log each line as it's run, making it easier to follow what's going on with logic errors. (One caveat is that when running as root, modern versions of bash don't allow `PS4` to be inherited via the environment for security reasons, so you need to put that assignment in your code to get the logs to include line number). – Charles Duffy Nov 17 '18 at 20:19

1 Answers1

0

Your code will always report "The address does not match". If the address matches $IPnode1, then it doesn't match $IPnode2, and vice versa. You should only execute the second test when the first one fails.

if [[ "$IPv4" = "$IPnode1" ]]; then
    echo "found the address "
    echo "$IPnode1   VM01.com VM01" >> /etc/hosts
elif [[ "$IPv4" = "$IPnode2" ]]; then
    echo "found the address "
    echo "$IPnode2   VM02.com VM02" >> /etc/hosts
else
    echo "The address does not match"
fi
Barmar
  • 741,623
  • 53
  • 500
  • 612