[Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 224
  • Last Modified:

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???
2 Solutions
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

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!
jl66Author Commented:
Thanks a lot for the solution. very helpful.

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now