I am trying to parse the "number of hops" value from the traceroute
command and output it with a bash script.
Any hints? Very new so thanks.
My script looks like this so far:
#!/bin/bash
#parse traceroute for hops and output to stdout.
echo -n "Enter a host name(like www.google.com): "
read hostname
traceroute 2>&1 $hostname|grep "hops"
echo "number of hops are "
Are you looking for the number of hops it took, or the "64 hops max" value? If it's the former, use tail
to get the last line of output, then awk
to print the first column:
traceroute "$hostname" 2>/dev/null | tail -1 | awk '{print $1}'
The only occurrence of "hops" in traceroute output (stderr, actually) is towards the top, in the stderr "header" line:
traceroute to foo.bar.com (123.12.1.23), 30 hops max, 40 byte packets
or the like -- if that's the one line you want to grab, you might grep for "hops max,"
or the like in order to reduce the risk of undesired hits (should some intermediate host just happen to have "hops" in their DNS).
Is this what you mean? Is your problem grabbing this 30, the maximum number of hops, into a bash variable? If that's so, then
maxhops=`traceroute www.yahoo.com 2>&1 >/dev/null | grep "hops max" | cut -d' ' -f5`
should help -- you can use $maxhops
after this (and it will be 30 in the above example).
But I suspect you mean something completely different -- clarify, maybe...?
Edit: the OP has clarified they want, not maxhops, but the actual number of hops as measured by traceroute; for that purpose,
numhops=`traceroute www.yahoo.com 2>/dev/null | tail -1 | cut -d' ' -f2`
or a simpler
numhops=`traceroute www.yahoo.com | wc -l`
should work fine!
If you do want anything fancier (or more than one result, etc) then awk as suggested in other answers is perfectly fine, but a pipeline mix of grep, tail, and cut, is quite a traditional unix-y approach, and still quite workable for simple cases (and some complex ones, but awk or perl may be more appropriate for those;-).
traceroute www.google.com 2>/dev/null | awk 'NR==1{print $5;exit}'
another way, where those hops not reachable (for lack of better word) are not counted
# traceroute www.yahoo.com 2>/dev/null | awk 'NR>1 && !/* * */{c++}END{print c}'
16
来源:https://stackoverflow.com/questions/1183625/parsing-data-from-traceroute-command