2

I have the following script that is trying to match and IP address with a value in a file

#!/usr/bin/env bash

#To find the IP via ping
ping=$(ping federicolivieri.noip.me -c 1)
#To cut the result
ip=$(echo ${ping} | awk '{print $3}' | rev | cut -c2- | rev | cut -c2-)
#dnsdist variable
dnsdist_ip=$(awk 'END{print $1}' /etc/dnsdist/dnsdist.conf | cut -c 19- | rev | cut -c 2- | rev)

if [ "$ip" -eq "$dnsdist_ip" ]; then
   echo "ciao"
   else
   echo "newServer{address="`echo ${ip}`", name="raspi"}" >> /etc/dnsdist/dnsdist.conf
fi

However, when I run the script I get this error

root@raspberrypi:/etc/myscripts# ./noip.sh
./noip.sh: line 10: [: 2.31.237.195: integer expression expected

I understood that the script expect a integer numeric value but as you know, IP address as "dots"

How can I workaround this problem?

  • 1
    For information about testing for string equality, see man test – steeldriver Apr 21 '16 at 15:46
  • or use plain old = – Archemar Apr 21 '16 at 15:46
  • 2
    If the number of digits in your IP address ever changes, your cut -c19- will break. You'd be safer matching against the field name address like this - dnsdist_ip=$(sed -n '$s!^.*address=\([1-9][0-9.]*\).*!\1!p' /etc/dnsdist/dnsdist.conf) – roaima Apr 21 '16 at 16:02
  • Hi roaima, The first 19 characters will never change because is a fix text, Anyway I take in account about your suggestion – Federi Apr 21 '16 at 16:13
  • @roaima is right, your cut usage here is brittle. You're already using awk to grab only the first whitespace-separated field; why do you need to drop the last character of it? (If you really do need to drop the last character, I'd still recommend ending that pipeline with the awk command and following up with dnsdist_ip=${dnsdist_ip%?} instead of the non-portable rev.) – Wildcard Apr 21 '16 at 22:38
3

As Archemar pointed out in his comment, you want to use = for string comparison:

if [ "$ip" = "$dnsdist_ip" ];

The -eq operator is for numerical comparison, as explained here:

n1 -eq n2

True if the integers n1 and n2 are algebraically equal; otherwise, false.

Since IPs are not integers (they also contain .), you can't use -eq to compare them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.