A Fish Script for Alerting when Network Connectivity Changes
The ping command has a switch -a for an audible ping that rings the terminal bell with each response received, but that’s annoying. What we want more often is to be alerted when the situation changes.
This script will ring the terminal bell once when the packets start getting lost and then rings it again when packet receipt resumes. It takes at least one argument, the destination to ping.
#!/usr/bin/env fish
while true
# Ping and print 1 line with the time and the result.
echo -n (date "+%I:%M:%S ")
ping -c 1 -W 5 -q $argv | grep 'packets transmitted' --color=never
set thisStatus $pipestatus[1]
# In case there is an unrecoverable error on first run.
if test \( "$thisStatus" -eq 2 -o (count $argv) -lt 1 \) -a -z "$prevStatus"
break
end
# If the status has changed, ring the bell.
if test -n "$prevStatus" -a "$thisStatus" -ne "$prevStatus"
echo -ne "\a"
end
# Ping slower if the connection is up.
if test "$thisStatus" -eq 0
sleep 10
else
sleep 1
end
set prevStatus $thisStatus
end
What I learned from writing this in fish is that test is weird and I don’t like fish scripting anymore.
Some versions of ping when invoked without a destination will return code 2 and others (ping from iputils 20240117) will return code 1. This is probably a bug in ping because the man page says “On other error it exits with code 2.”