How to catch the error message in Linux with SHELL commands

Want to process the error message from issuing commands. For example,

ping 10.10
connect: Network is unreachable

My question is how to get "connect: Network is unreachable" out.

I tried to use the similar idea like

ls > test.log

I can see a lot of files/directories with "cat test.log", but it did not work for

ping 10.10 >test.log

If I see it, test.log is an empty file.

Which commands can catch the error message or pipe somewhere???
Who is Participating?
xtermConnect With a Mentor Commented:
A Unix command generates normal output, and error output, referred to as stdout and stderr.

When you do "ping 10.10 > test.log"  you are redirecting stdout to the log file.

This is great if the host responds, but it doesn't help you if the command fails.  For that you need to do:

ping 10.10 2> /test.log

See, 1> is stdout, and 2> is stderr.  You can direct both to different places like:

ping 10.10 1>success.log 2> error.log

Or if you like, you can combine them like this:

ping 10.10 1> ping.log 2>&1

One of those should get you what you need, good luck!
maeltarConnect With a Mentor Commented:
This does what I think you are looking for :

for ip in 192.168.1.{1..10}; do
    ping -c 1 -t 1 $ip > /dev/null 2> /dev/null  # ping and discard output
    if [ $? -eq 0 ]; then  # check the exit code
        echo "${ip} is up" >>test.log # display the output
        echo "${ip} is down"

Open in new window

jl66Author Commented:
Thanks a lot for the solution. very helpful.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.