Skip to content

Instantly share code, notes, and snippets.

@rwohleb
Created May 23, 2025 19:01
Show Gist options
  • Save rwohleb/3d8242a7aaffa92aa76c90a238d4850f to your computer and use it in GitHub Desktop.
Save rwohleb/3d8242a7aaffa92aa76c90a238d4850f to your computer and use it in GitHub Desktop.
Run traceroute upon detecting ping failure
#!/bin/bash
# Run this script with the following command:
# while true; do ./ping_and_trace.sh; sleep 1; done
# Set the host to ping
HOST="1.1.1.1"
PING_COUNT=5
# Get current time
CURRENT_TIME=$(date "+%Y-%m-%d %H:%M:%S")
# Run ping and capture output
PING_OUTPUT=$(ping -c $PING_COUNT $HOST)
# Extract packet loss percentage
PACKET_LOSS=$(echo "$PING_OUTPUT" | grep -oE '[0-9]+\.?[0-9]*% packet loss' | grep -oE '^[0-9]+\.?[0-9]*')
# Check if packet loss is greater than 0
if [[ $(echo "$PACKET_LOSS > 0" | bc) -eq 1 ]]; then
echo "[$CURRENT_TIME] Packet loss detected ($PACKET_LOSS%). Running traceroute to $HOST..."
traceroute $HOST
else
echo "[$CURRENT_TIME] No packet loss detected ($PACKET_LOSS%)."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment