Ping once and return true/false

The ping command will usually try pinging a device forever, returning the response time after each pingback. If you want to ping a device once and use the answer to perform an action, use the following snippet:

ping -c 1 [your ip or hostname] > /dev/null

This command will either return 1 on failure or 0 on success.

In the example below, we use the && operator to perform an action if and only if the ping to “homeserver” was successful:

ping -c 1 homeserver >/dev/null && echo 'Successfully pinged device!'

This can be a great way to monitor the presence of a device on the network for a dead man’s switch for example.

One comment on “Ping once and return true/false

  1. If you want to output a message on success and another on error, you can do it with the following syntax :

    ping -c1 8.8.8.8 2> /dev/null && echo 'Connected' || echo 'Disconnected

    So that when you are disconnected, you get the following message :

    Disconnected

    If the script was like that :

    ping -c 1 8.8.8.8 /dev/null && echo 'Connected' || echo 'Disconnected'

    The standard error and the command result would appear in the console like so :

    connect : network is unreachable

    Disconnected

    And that’s not what we want

    This is also useful for script like PHP that needs to get a boolean as a value :

    $connected = shell_exec('ping -c1 8.8.8.8 2> /dev/null && echo "true" || echo "false"');

    And the result would be a boolean, either true or false.

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax