Help with script that maps routes

0

I made a script that traces the route of a certain IP, but with the while going to 50, even if the connection has an 8-route jump, it will count to 50, how do I stop the while when I finish number of routes?

#!/bin/bash
echo "Digite um IP: "; read ip
count=1;
while [ $count -lt 50 ]; do
    ping $ip -t $count -c 1 | grep ^From | awk '{print $2}'

let count=$count+1;
done
    
asked by anonymous 15.05.2017 / 14:53

1 answer

1

We can work with the Exit Status of your command, which is the value returned by the waitpid system call, and helps us understand if this was successful or not.

In this case, we could add the Logical Operator & & , as follows:

#!/bin/bash
echo "Digite um IP: "; read ip
count=1;
while [ $count -lt 50 ]; do
    ping $ip -t $count -c 1 | grep ^From | awk '{print $2}' && break

let count=$count+1;
done

Explanation of the changed line:

ping $ip -t $count -c 1 | grep ^From | awk '{print $2}' && break

The break command will only be executed if ping return 0 (zero).

That way, once the ping encounters the smallest TTL, the loop will be broken.

Simple proof of concept for ping:

$ ping google.com -t 9 -c 1
PING google.com (172.217.30.14) 56(84) bytes of data.
64 bytes from rio01s23-in-f14.1e100.net (172.217.30.14): icmp_seq=1 ttl=55 time=5.16 ms

--- google.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 5.161/5.161/5.161/0.000 ms

$ echo $?
0

$ ping google.com -c 1 -t 8
PING google.com (172.217.30.14) 56(84) bytes of data.

--- google.com ping statistics ---
1 packets transmitted, 0 received, 100% packet loss, time 0ms

$ echo $?
1
    
21.09.2017 / 03:27