Search code examples
arraysbashgreptraceroute

Compare traceroute IP with array values


I am trying to compare if traceroute got successful or not in a bash. This is what I execute.

traceroute -m 30 -n 8.8.8.8 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+'

Output I receive:

8.8.8.8

8.8.8.8

192.192.192.21

192.191.191.32

192.18.128.48

8.8.8.8

192.168.168.168

I want to compare 8.8.8.8 (first value of the array) with last 3 values of the array, but when I try it, I get the error for float comparison.

Edit:

I tried this code, but it gives me error for float comparison.

for i in ${my_array[@]};
do
        if [ "${my_array[0]}" == "${my_array[i+1]}" ]; then
                echo "values are same";
        else
                echo "values are not same";
        fi
        echo $i;    
done

I know it is possible to use "bc" to solve float comparison problem, but is there any other way to solve this inline rather than storing it in an array ?


Solution

  • You may use this awk for your requirement:

    traceroute -m 30 -n 8.8.8.8 |&
    awk '$1=="traceroute"{ip=$3} /ms$/{a[++n] = ($1+0 == $1 ? $2 : $1)}
         END{for (i=n-2; i<=n; i++) if (ip == a[i]) exit 1}'
    

    It will exit with status 1 when any IP address in last 3 lines match with IP in first line that starts with traceroute. If there is no match then exit status will be 0.