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

Issue

I have a list of ip addresses in .txt format

162.243.217.39
170.175.178.13
235.169.86.84
218.820.241.164
104.89.61.87
254.217.220.124

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

Solution

Assumptions:

  • 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 >>

Examples:

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

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

$ head correct.txt error.txt
==> correct.txt <==
PING yahoo.com (98.137.11.164): 56 data bytes
64 bytes from 98.137.11.164: icmp_seq=0 ttl=48 time=281.624 ms
64 bytes from 98.137.11.164: icmp_seq=1 ttl=48 time=239.202 ms
--- yahoo.com 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
    then
        do some other stuff
    else
        do some other stuff
    fi
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