Blog Tags: 

Two simple ways a script can detect if it's online

I didn't want installation of one of TurnKey's components to freeze up too long if it was installed offline so I looked for a nice way to detect that without bringing in additional dependencies.

Two methods stood out...

  1. ping Google DNS servers: one second constant delay, regardless if you're online or off:

    # will be true if we're online. Will send 5 packets total.
    is_online() {
        ping -w 1 -i 0.2 > /dev/null
  2. try to resolve a hostname: this will return very quickly if online, 2-3 seconds if we're not, assuming we pass the right args to "host":

    is_online() {
        if 2>&1 host -h | grep -q -- -W; then
                command="host -W 1"
                command="host -s 1"
        $command >& /dev/null

Since I figured we'd be online more often then not I optimized for that and chose the second method.


Tom Davidson 's picture

What about using "getent hosts" as an simpler alternative to option 2? Return code is 0 for success and 2 (in my testing) for failure. is_online() { getent hosts > /dev/null }
Liraz Siri's picture

Thanks for the suggestion Tom. Your one-liner is an improvement. I didn't realize you could use getent for this. Nice!

Peter's picture

1. You can be perfectly online while not able to ping outside your organization's network.

2. Resolving a fqdn looks more stable solution, but still you can be temporarily offline while your dns cache returns the host's data.




Add new comment