1

I have several Raspberry Pi's named numerically (pi0, pi1, etc). They have static IP addresses, but I wanted a simple tool to check on them and make sure they were online even if they got the wrong IP (I've had some trouble in the past. Nothing recently, but it seemed like a good idea to make it foolproof regardless). Instead of using IPs, this tool uses MDNS hostnames that are already in a nice format. The script I wrote is:

#!/bin/bash

report+="Device Name     Status       Location\n"
report+="-----------     ------       --------\n"

for i in {0..3}
do
    report+="Pi$i             "
    ping -c1 pi$i.local > /dev/null
    if [ $? == 0 ]
    then
        report+="Online       "
        report+=$(ping -c1 pi$i.local | grep -o "\w*192.168.1.\w*" | head -1)
    else
        report+="Unreachable"
    fi
    report+="\n"
done
echo -e "$report"

It works wonderfully when devices are online, returning

Device Name     Status       Location
-----------     ------       --------
Pi0             Online       192.168.1.3
Pi1             Online       192.168.1.4
Pi2             Online       192.168.1.5
Pi3             Online       192.168.1.6

However, when they are offline the output looks like this

ping: pi0.local: Name or service not known
ping: pi1.local: Name or service not known
ping: pi2.local: Name or service not known
ping: pi3.local: Name or service not known
Device Name     Status       Location
-----------     ------       --------
Pi0             Unreachable
Pi1             Unreachable
Pi2             Unreachable 
Pi3             Unreachable

Is there a way to suppress the "Name or service not known" for the MDNS lookup on the ping? I already direct output to /dev/null, so I don't see how it is still giving output.

Alternatively, if you have a better/faster/easier/prettier way to do this checking, I'd love to hear it.

  • 1
    Add 2>&1 after your > /dev/null. – dsstorefile1 May 10 '18 at 0:36
  • 1
    Redirect stderr to /dev/null ? ping -c1 pi$i.local > /dev/null 2> /dev/null ... of course, there are other ways of redirecting (redirect error to out, redirect out to null like you are doing, etc) – ivanivan May 10 '18 at 0:37
  • 1
    @dsstorefile1 not gonna lie, I'm a little disappointed this was so simple. Guess my google-fu needs a little improvement! – brndn2k May 10 '18 at 0:40
1

As was briefly pointed out in the comments, ping is displaying that message to stderr, which you had not redirected. Do so with:

...
ping -c1 pi$i.local > /dev/null 2>&1
...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.