The mtr
command has two default output modes that aren't ideal for scripting:
- Graphical GTK window interface (default)
- Interactive ncurses terminal interface (
-t
flag)
Both modes create issues for developers who need to:
mtr example.com | grep "packet loss"
mtr -c 5 google.com > trace_results.txt
Use the --report
or -r
flag for script-friendly output:
mtr --report example.com
mtr -rw -c 10 google.com
The key flags to combine:
-r/--report
: Enables report mode-w/--report-wide
: Shows full hostnames-c COUNT
: Sets number of pings per hop
This command provides clean, parseable output:
mtr -rw -c 5 8.8.8.8 | tee dns_trace.log
For JSON output (requires mtr 0.90+):
mtr --json example.com | jq '.report.hubs[] | select(.LossPct > 0)'
CSV output alternative:
mtr -rwc 1 example.com | awk '!/Start|HOST/ {print $1","$2","$3"%"}' > trace.csv
If you see terminal control characters:
mtr -r example.com | col -b > clean_output.txt
For older mtr versions (pre-0.82):
mtr --no-dns -r example.com
When running mtr
(My Traceroute) on Linux systems, the default behavior often frustrates sysadmins and developers who want clean, pipeable output. The two main interface options - GTK and NCURSES - both interfere with standard UNIX output redirection.
# What happens when you try basic redirection
$ mtr google.com > output.txt
$ cat output.txt # Contains terminal control chars like ESC[?1049h
MTR actually has built-in options for raw output, but they're not well documented. Here's the combination that works:
# Report mode with CSV output (best for parsing)
$ mtr --report --csv google.com
# Alternative: Standard report format
$ mtr --report google.com
# Force single cycle and show IPs (good for quick checks)
$ mtr --report -c1 -b google.com
To avoid typing flags repeatedly, configure defaults in /etc/mtr.conf
:
# Sample configuration for script-friendly output
report-mode=1
displaymode=1 # 0=GTK, 1=NCURSES, 2=RAW
interval=1.0
timeout=10
Here's how to process MTR output in shell scripts:
# Extract latency stats per hop
mtr --report -c5 google.com | awk '/^h/ {print $2,$3,$4}'
# Continuous monitoring with alerting
while true; do
mtr --report -c1 api.service.com | \
grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | \
awk '$7 > 100 {system("send-alert.sh High latency at " $1)}'
sleep 300
done
- Missing hostnames: Use
-z
flag for DNS resolution - IPv6 problems: Force IPv4 with
-4
or IPv6 with-6
- Timeout adjustments:
-u
for UDP,-T
for TCP,-P
for specific ports