I have a simple script that checks if an interface is connected:

connected=$(ping -I $1 -qc 1 \
  && echo "connected" \
  || echo "not connected")

echo "$connected" | tail -n1

I'm expecting that it should simply return "connected" or "not connected". When I actually use the script I always get back a warning before my output.

ping: Warning: source address might be selected on device other than enp0s25.
not connected

What is with the warning here, shouldn't it be part of the subshell?

  • 4
    Aside from redirecting standard error, wouldn't it be much simpler as if ping ... ; then echo "connected" ; else echo "not connected"; fi? – Nate Eldredge Nov 12 '17 at 1:28

The warning is sent to ping’s standard error, which isn’t captured. If you want to ignore it, redirect it to /dev/null explicitly:

connected=$(ping -I $1 -qc 1 2>/dev/null \
  && echo "connected" \
  || echo "not connected")

echo "$connected" | tail -n1
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.