Hide error messages

Asked

Viewed 437 times

3

Consider the following shell script:

ping  8.asd.8.8 -c1 -q > /dev/null
if [ $? == 0 ]
then
echo 'ok'
else
echo 'erro'
fi

This ping will return an error and this error is dealt with in else right below. But even using the parameter -q the error returned by ping is written on the screen:

ping: unknown host 8.asd.8.8

Is there any way to ignore this error? Show only the error handled by if?

2 answers

4

Redirect error output to /dev/null:

ping 8.asd.8.8 -c1 -q 2>/dev/null
if [ $? == 0 ]
then
echo 'ok'
else
echo 'erro'
fi

More information: What is and what is it for "2>&1"?

3


Use the &>, that in addition to redirecting the standard output (stdout), redirects errors as well (stderr):

ping  8.asd.8.8 -c1 -q &> /dev/null
  • The -q in this case it should not be necessary as the stdout and stderr will be redirected to /dev/null.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.