Skip to content
TURNKEYGNU / LINUX
AppsDocumentationBlogScreenshotsGitHubTurnKey Hub
文English
EnglishDeutschEspañol日本語Português中文
Home/Blog/Two simple ways a script can detect if it's online

From the project

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

By Liraz SiriSeptember 1, 20141 min read
developmentscript

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 8.8.8.8 > /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"
        else
                command="host -s 1"
        fi
    
        $command pool.ntp.org >& /dev/null
    }
    

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

Comments (1)

I like it!

Reply 1 2014-09-03

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

Keep exploring

Find your next server

Browse ready-to-use appliances by the job you need to do.

Explore the app library
TURNKEYGNU / LINUX

Own your infrastructure without starting from scratch.

Explore TurnKey
AboutDocumentationFAQBlogGitHub
Free and open sourceSecure by defaultReady to deploy