Bash Ping

Ping sends ICMP echo requests to a remote host so you can check reachability and measure round-trip latency straight from the terminal.

What Ping Does

The ping command sends a small ICMP (Internet Control Message Protocol) echo request packet to a target host and waits for an echo reply. If replies come back, the host is reachable over the network and you get a round-trip time in milliseconds; if nothing comes back, the packet was lost, blocked, or the host is unreachable.

Sending a Continuous Ping

On most Linux distributions, running ping with just a hostname or IP address sends one packet per second forever. Press Ctrl+C to stop it and print a summary of the session.

Pinging a Domain

$ ping google.com
PING google.com (142.250.183.14) 56(84) bytes of data.
64 bytes from lhr25s12-in-f14.1e100.net (142.250.183.14): icmp_seq=1 ttl=115 time=11.4 ms
64 bytes from lhr25s12-in-f14.1e100.net (142.250.183.14): icmp_seq=2 ttl=115 time=10.9 ms
64 bytes from lhr25s12-in-f14.1e100.net (142.250.183.14): icmp_seq=3 ttl=115 time=12.0 ms
^C
--- google.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 10.900/11.433/12.000/0.457 ms

Reading the Output

  • icmp_seq - the sequence number of each packet, useful for spotting drops in the middle of a run
  • ttl - Time To Live, the number of network hops the packet can still make before being discarded
  • time - the round-trip time in milliseconds between sending the request and receiving the reply
  • packet loss - the percentage of requests that never got a reply, shown in the closing statistics

Limiting Packets and Checking Reachability in Scripts

Continuous ping is fine interactively, but in scripts you want a fixed number of attempts and a short timeout. The -c flag stops ping after the given count, and -W sets how many seconds to wait for each reply, which makes the exit status meaningful for automation.

Pinging a Fixed Number of Times

$ ping -c 4 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=118 time=9.42 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=118 time=9.71 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=118 time=9.35 ms
64 bytes from 8.8.8.8: icmp_seq=4 ttl=118 time=9.88 ms

--- 8.8.8.8 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3005ms
rtt min/avg/max/mdev = 9.350/9.590/9.880/0.211 ms

Checking Reachability with an Exit Status

$ ping -c 1 -W 2 8.8.8.8 > /dev/null 2>&1
$ echo "Exit status: $?"
Exit status: 0
$ ping -c 1 -W 2 10.255.255.1 > /dev/null 2>&1
$ echo "Exit status: $?"
Exit status: 1
Note: A failed ping does not always mean a server is down. Many production servers and firewalls block ICMP traffic entirely for security reasons while still answering HTTP or SSH requests normally, so pair ping with curl for a fuller picture.