Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading