Ping: redirect output and error

Hi, I use this function (now modified with elif) for check if a pc is up:

check_pc() {
 
  $PING $PC 1 2> /dev/null

  if [ $? -eq 0 ]; then
   
    check_dir #Other function
   
    echo "Begin backup operation for $PC"

    echo "$SMBTAR -s $PC -u $USER -p $PASS -x $SHARE$EXCL -t - | gzip -c > $PC.tar.gz"
   
    echo "End backup operation for $PC"
    echo ""    

  elif [ $? -eq 1 ]; then  
     
    echo "Unable to ping $PC"
    echo ""

  else  
    #Not in /etc/hosts
    echo "Unable to find $PC"
    echo ""

  fi

} #end check_pc

But.. With

$PING $PC 1 2> /dev/null

output like no answer from pc3 don't finish in /dev/null ... If I try

$PING $PC 1 > /dev/null

don't finish in /dev/null /usr/sbin/ping: unknown host pc123. How redirect error and output in /dev/null?
And.. can I use ping error to write in a log file "Unable to find $PC".. now the last else don't work. I use /bin/sh ... Thanks, bye.

You can redirect output and error mode data into /dev/null as,

ping <IP> 1>/dev/null 2>&1
ping <IP> 1>/dev/null 2>/dev/null

ping <ip> 1>/tmp/logfile 2>&1
it will redirect into /tmp/logfile

ping <ip> 1>/tmp/logfile 2>errorfile
output to logfile and error to errorfile.

HTH.

Ok, it works. :slight_smile:

If I want do something for 0, 1 or 2 ping result? Like

if [PINGOK]

  //do_something

elif [PINGRETURN1]

  //do_something1

else #error

  //do_something2

:confused:

You can get the result code from ping as,

ping <ip> 1>/dev/null 2>&1
ret=$?

if [[ $ret -eq 2 ]]
then
action..
elif [[ $ret -eq 1 ]]
then
action
elfi [[$ret -eq 0 ]]
then
action..
fi

HTH.