ben shalev
ben shalev

Reputation: 103

Else if conditional does not apply in awk

ping 8.8.8.8 -t 5 -c1 | awk '{if (/Time.*/) print $1,$2; else if (NR==1) print "from: " $3 " "}'

When i use this line the else if doesn't work, it basically prints from and the ip no matter what first, even before the if conditional. I want it print it only when the TTL is enough to reach the target (Or when there isn't a message involving Time to live exceeded)

This command is basically a traceroute written by me.

I don't know why the else if conditional doesn't work, i would love help.

The whole bash script:

#! /bin/bash

read -p 'IP: ' IP
read -p 'Max hops: ' hops

for hop_num in $(seq 1 $hops)
do
        if [[ $IP =~ [0-9] ]];then
                echo "$hop_num " | tr -d '\n'
                ping $IP -t $hop_num -c1 | awk '{if (/Time.*/) print $1,$2; else if (NR==1) print "Dest: " $3 " "}'
            
        else
                echo "not matched"
        fi
done

Ping output without awk filter:

PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
From 10.250.99.2 icmp_seq=1 Time to live exceeded

--- 8.8.8.8 ping statistics ---
1 packets transmitted, 0 received, +1 errors, 100% packet loss, time 0ms

Upvotes: 0

Views: 137

Answers (2)

choroba
choroba

Reputation: 241768

That's expected. The first line doesn't match Time.* but NR is 1, as it's the first line. Therefore, $3 is printed, which happens to be (8.8.8.8).

On the following lines, NR is never 1 again, so only the when the line matches Time.*, you'll get the output.

To fix the problem, remember the IP on the first line, and print it at the end if you didn't print anything.

awk '(NR==1){f=$3}(/Time/){print$1,$2;p=1}END{if(!p)print f}'

f is used to remember the IP from the first line, p is the flag that tells us whether we printed anything.

Upvotes: 1

Pierre François
Pierre François

Reputation: 6061

Try:

ping 8.8.8.8 -t 5 -c1 | awk '/Time/{print $1,$2}(NR==1){print "from: " $3 " "}

Upvotes: 0

Related Questions