How can I split descriptors (0/1 and stderr) into 2 different files while pinging in linux


I have a list of ip addresses in .txt format

It is necessary to ping IP addresses and sort those that give an error 2 (stderr) and a working result into two files.

I think it should look something like this:

while IFS= read -r ip; do
    if ping -c4 $ip == 0 ||ping -c4 $ip == 1
    then >> correct.txt
    else >> error.txt
done < ip_list.txt

But I don’t understand how to do it correctly in terms of syntax



  • want to capture the stdout and stderr from all ping calls into files correct.txt and error.txt, respectively
  • need to test/respond-to the return code of the ping calls

Generally speaking:

ping ....  >> correct.txt 2>> error.txt

NOTE: no space between 2 and >>


$ ping -c2 >> correct.txt 2>> error.txt
$ echo $?

$ ping -c2 >> correct.txt 2>> error.txt
$ echo $?

$ head correct.txt error.txt
==> correct.txt <==
PING ( 56 data bytes
64 bytes from icmp_seq=0 ttl=48 time=281.624 ms
64 bytes from icmp_seq=1 ttl=48 time=239.202 ms
--- ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max/stddev = 239.202/260.413/281.624/21.211 ms

==> error.txt <==
ping: unknown host

The echo $? output shows we still have access to the return code so if you need to perform other actions in your script then this should suffice:

while IFS= read -r ip; do
    if ping -c4 $ip >> correct.txt 2>> error.txt
        do some other stuff
        do some other stuff
done < ip_list.txt

Answered By – markp-fuso

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published