Check Network Connection in Bash

September 15th 2014

Bash is great, and interacting with webservices is fairly easy. Of course, to do that you will need to know whether the user is connected to the web.

So, to check the network connection in Bash I typically use a simple ping against the primary Google DNS server (8.8.8.8).

Text Snippet:
#!/usr/bin/env bash
PUNG=`ping 8.8.8.8 -c1 > /dev/null 2>&1`
if [ $? -eq 0 ]; then
  echo "Looks like you're connected!"
else
  echo "No connection."
fi

And that's it. Fairly easy to use, simple to understand, and quite reliable (from my experience).

If you have any suggestions, or comments, feel free to leave them below.