RSSAmplifier

aryan's blog · May 27, 2025

Enhanced ping with timestamp

0
Sign in to vote or save

This site does not allow itself to be embedded. You can still read it on the original site — the toolbar below keeps your place in the directory.

I usually have this running all the time in a terminal. Super handy to keep an eye out in case of network drop outs.

This is a fish function:

function tsping --description "Continuous ping with colored timestamps"
    # Configuration
    set -l timestamp_color cyan
    set -l success_color green
    set -l error_color red
    set -l host_color yellow
    set -l default_host "google.com"
    # Parse arguments
    set -l ping_args
    set -l host $default_host
    set -l help_flag 0
    argparse -n tsping 'h/help' -- $argv
    or return 1  # Abort if argparse fails
    if set -q _flag_help
        echo "Usage: tsping [PING_OPTIONS] [HOST]"
        echo "Options:"
        echo "  -h/--help    Show this help"
        echo "  Any other ping options (e.g., -i 2, -c 5)"
        echo "Examples:"
        echo "  tsping                         # Ping google.com"
        echo "  tsping example.com             # Ping example.com"
        echo "  tsping -i 0.5 8.8.8.8          # Ping every 0.5 seconds"
        return 0
    end
    # Extract host from last argument if it's not a flag
    for arg in $argv
        if test -z (string match -r '^-' $arg)
            set host $arg
        end
    end
    # Build ping arguments (exclude the host)
    set ping_args (string match -v $host -- $argv)
    # Check if ping exists
    if not command -q ping
        echo (set_color $error_color)"Error: ping command not found"(set_color normal) >&2
        return 127
    end
    # Run ping with colors
    ping $ping_args $host | while read -l line
        # Colorize different parts
        set -l timestamp (set_color $timestamp_color)(date "+%Y-%m-%d %H:%M:%S")(set_color normal)
        set -l colored_line (string replace -r '(\d+ bytes from .+? \([\d.]+\))' (set_color $success_color)'$1'(set_color normal) "$line")
        set colored_line (string replace -r '(time=[\d.]+ ms)' (set_color $success_color)'$1'(set_color normal) "$colored_line")
        set colored_line (string replace -r '([\d.]+% packet loss)' (set_color $error_color)'$1'(set_color normal) "$colored_line")
        set colored_line (string replace -r "($host|$default_host)" (set_color $host_color)'$1'(set_color normal) "$colored_line")
        echo "$timestamp $colored_line"
    end
end

If you are using bash/zsh, this doesn't have all the bells and whistles of above but it should work fine:

This is the bash compatible version

ping www.google.com | while read pong; do echo "$(date): $pong"; done

#fish #shell #sysadmin

Read on blog.ameri.coffee

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.