Help with script tracing routes

Asked

Viewed 71 times

0

I made a script that plots the route of a given IP, but with the while going up to 50, even if the connection has a jump of 8 routes, it will count up to 50, as I do to stop the while when finishing the 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

1 answer

1

We can work with the Exit Status of your command, which is the value returned by the system call waitpid, 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 amended line:

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

Only the command will be executed break if the ping return 0 (zero).

That way, once ping finds 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.