71

I want to write a script, that would keep checking if any of the devices in network, that should be online all day long, are really online. I tried to use ping, but

if [ "`ping -c 1 some_ip_here`" ]
then
  echo 1
else
  echo 0
fi

gives 1 no matter if I enter valid or invalid ip address. How can I check if a specific address (or better any of devices from list of ip addresses) went offline?

burtek
  • 1,932
  • 4
  • 26
  • 31

10 Answers10

71

Ping returns different exit codes depending on the type of error.

ping 256.256.256.256 ; echo $?
# 68

ping -c 1 127.0.0.1 ; echo $?
# 0

ping -c 1 192.168.1.5 ; echo $?
# 2

0 means host reachable

2 means unreachable

Eric Leschinski
  • 123,728
  • 82
  • 382
  • 321
StianE
  • 2,615
  • 17
  • 19
  • 1
    cool... I'm still new to scripting and thought that `if` in my code does check the exit code... – burtek Aug 08 '13 at 10:13
  • 2
    It does, your if will trigger the `echo 1` block on any non-0 exit code (all errors). But to figure out what kind of error it was you will to check the exact exit code. – StianE Aug 08 '13 at 10:18
  • 3
    Do you get `68` on the first? I get `2` and unknow host. I get `1` on third example with Destination Host Unreachable. – nephewtom Nov 06 '17 at 18:37
  • I see the return code 68 on MacOS, but it is 2 on Linux for unresolvable hostname. There is also the -o option on MacOS (I assume in BSD also) which returns after a single successful packet. – Peter B Mar 23 '19 at 01:05
61

You don't need the backticks in the if statement. You can use this check

if ping -c 1 some_ip_here &> /dev/null
then
  echo 1
else
  echo 0
fi

The if command checks the exit code of the following command (the ping). If the exit code is zero (which means that the command exited successfully) the then block will be executed. If it return a non-zero exit code, then the else block will be executed.

user000001
  • 28,881
  • 12
  • 68
  • 93
  • I suggest replacing "&>" with ">", or else the script will continue running. – TNT Sep 05 '19 at 12:12
  • 3
    @TNT It depends on the shell. In bash `&> file` is equivalent to `> file 2>&1`, i.e. redirects both standard output and and standard error. – user000001 Sep 05 '19 at 12:16
24

There is advanced version of ping - "fping", which gives possibility to define the timeout in milliseconds.

#!/bin/bash
IP='192.168.1.1'
fping -c1 -t300 $IP 2>/dev/null 1>/dev/null
if [ "$?" = 0 ]
then
  echo "Host found"
else
  echo "Host not found"
fi
Fedir RYKHTIK
  • 9,110
  • 6
  • 53
  • 64
  • 1
    `ping` also has a -t option that allows you to define a timeout. – Tim Dearborn Oct 10 '14 at 17:28
  • 6
    True. But in seconds. `fping` - in milliseconds, thats important if You have lots of hosts to ping. – Fedir RYKHTIK Oct 12 '14 at 20:04
  • 1
    In "unixy" ping `-t` isn't for the timeout, but for the TTL. The timeout is specified via -W. Note: this can still block for a long time, eg. if the DNS server goes away and a DNS name has to be resolved. With the recent attacks in mind this should be considered. – dom0 Oct 28 '16 at 08:51
  • 1
    Like many of the other answers here, this one has the antipattern `cmd; if [ $? = 0 ]; then ...` which is better and more idiomatically written `if cmd; then ...` -- the purpose of `if` and the other flow control statements in the shell is precisely to run a command and check its exit status. You should very rarely need to examine `$?` directly. – tripleee Mar 15 '17 at 13:50
  • 1
    I would not say it's an anti-pattern, it's more question of personal choice. As for me, a command in standalone line is more readable. – Fedir RYKHTIK Mar 20 '17 at 13:32
  • 1
    It is absolutely an anti-pattern. – William Pursell May 27 '19 at 17:26
24

I can think of a one liner like this to run

ping -c 1 127.0.0.1 &> /dev/null && echo success || echo fail

Replace 127.0.0.1 with IP or hostname, replace echo commands with what needs to be done in either case.

Code above will succeed, maybe try with an IP or hostname you know that is not accessible.

Like this:

ping -c 1 google.com &> /dev/null && echo success || echo fail

and this

ping -c 1 lolcatz.ninja &> /dev/null && echo success || echo fail
5

FYI, I just did some test using the method above and if we use multi ping (10 requests)

ping -c10 8.8.8.8 &> /dev/null ; echo $?

the result of multi ping command will be "0" if at least one of ping result reachable, and "1" in case where all ping requests are unreachable.

emirjonb
  • 183
  • 1
  • 11
  • Send the output to a file in /tmp, check it from a GUI like lxpanel and you've got an up/down indicator for your tray. Or lately I'm into loops like ping every 30 seconds then sound a bell character and quit when a ping succeeds. Maybe with Termux on an Android phone. It ceases to be a one-liner though. – Alan Corey Jan 07 '20 at 15:07
3

This is a complete bash script which pings target every 5 seconds and logs errors to a file.

Enjoy!

#!/bin/bash
        
        FILE=errors.txt
        TARGET=192.168.0.1

          touch $FILE
          while true;
          do
            DATE=$(date '+%d/%m/%Y %H:%M:%S')
            ping -c 1 $TARGET &> /dev/null
            if [[ $? -ne 0 ]]; then
              echo "ERROR "$DATE
              echo $DATE >> $FILE
            else
              echo "OK "$DATE
            fi
              sleep 5
          done
Mr Frog
  • 31
  • 1
2
up=`fping -r 1 $1 `
if [ -z "${up}" ]; then
    printf "Host $1 not responding to ping   \n"
    else
    printf "Host $1 responding to ping  \n"
fi
Pang
  • 8,605
  • 144
  • 77
  • 113
miltos
  • 21
  • 1
0

This seems to work moderately well in a terminal emulator window. It loops until there's a connection then stops.

#!/bin/bash

# ping in a loop until the net is up

declare -i s=0
declare -i m=0
while ! ping -c1 -w2 8.8.8.8 &> /dev/null ;
do
  echo "down" $m:$s
  sleep 10
  s=s+10
  if test $s -ge 60; then
    s=0
    m=m+1;
  fi
done
echo -e "--------->>  UP! (connect a speaker) <<--------" \\a

The \a at the end is trying to get a bel char on connect. I've been trying to do this in LXDE/lxpanel but everything halts until I have a network connection again. Having a time started out as a progress indicator because if you look at a window with just "down" on every line you can't even tell it's moving.

Alan Corey
  • 419
  • 3
  • 9
0
for i in `cat Hostlist`
do  
  ping -c1 -w2 $i | grep "PING" | awk '{print $2,$3}'
done
Community
  • 1
  • 1
helper
  • 1
0

I liked the idea of checking a list like:

for i in `cat Hostlist`
do  
  ping -c1 -w2 $i | grep "PING" | awk '{print $2,$3}'
done

but that snippet doesn't care if a host is unreachable, so is not a great answer IMHO.

I ran with it and wrote

for i in `cat Hostlist`
do
  ping -c1 -w2 $i >/dev/null 2>&1 ; echo $i $?
done

And I can then handle each accordingly.

Hoppeduppeanut
  • 933
  • 5
  • 17
  • 21
bpleat
  • 1
  • Welcome to Stack Overflow! For future reference, you should use the backtick character (\`) instead of the period character (.) to define code fences. This will fix your code block formatting. – Hoppeduppeanut Dec 10 '20 at 23:23
  • I don't believe I used a period in my snippet? – bpleat Dec 12 '20 at 00:46