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.


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!


Add new comment