Script help for tracing routes

Asked

Viewed 110 times

1

I am creating a script similar to tracerouce, when I type an IP it plots the route to arrive at the final destination, but when the route reaches the destination, the while still continues, as I correct this problem, stop when arriving at the final destination?

#!/bin/bash
echo "Digite um IP: "; read ip
count=1;
while [ $count -lt 30 ]; do
    ping $ip -t $count -c 1 | grep ^From | awk '{print $2}'
        if [ $? -eq 0 ]; then
            printf 'O salto é: '    
        else
        echo 'Rota Indisponível'
        fi
let count=$count+1;
done

1 answer

0

The problem is in the return variable '$? ', used in the conditional deviation. You are checking the return of the awk command, which always returns '0' in this case, so the loop will always run until $Count reaches 30. You can validate ping output after awk, such as changing your following script:

#!/bin/bash
echo "Digite um IP: "; read ip
count=1;
while [ $count -lt 30 ]; do
  ping $ip -t $count -c 1 | grep ^From | awk '{print $2}' | grep -P '^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'
    if [ $? -eq 0 ]; then
      printf 'O salto é: '
    else
      echo 'Rota Indisponível'
      exit
    fi
let count=$count+1;
done

Browser other questions tagged

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