4

I'm trying to get both successful and unsuccessful responses from a ping in a bash script but am unable to thus far.

My code looks like this...

ping_results=$(ping -c 4 -q google.com)

This works when the ping is successful, but if I don't have an internet connection and I get the result

ping: unknown host google.com

It is printed to the console, and my script appears to exit.

I want both the ping result or error to be stored in the ping_results variable.

Any help will be appreciated.

1
  • That is because errors go to stderr use something like 2&>1 t osend output to stdout Commented Mar 16, 2013 at 22:55

1 Answer 1

11

Okay, the simple answer to your question is to redirect stderr to stdout. as what Fredik Phil mentioned in the comments.

instead of:

ping_results=$(ping -c 4 -q google.com);

use:

 ping_results=$(ping -c 4 -q google.com 2>&1);

or something similar...

However, depending on what you're doing, it might be better to test if the exit code of the ping command is 1 (indicating that the ping is ending in an error), or 0 (indicating that the ping is successful). the exit code is stored in the variable "$?".

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.