I've been writing a script whose weird behavior's been driving me nuts, but I've managed to find what might be the problem: command substituting like this
out="$(ping google.com)"
if done while the internet isn't available, outputs this to the terminal
ping: google.com: Temporary failure in name resolution
even though, from my understanding, the command being substituted is run in a subshell, and so the output of the command should not go to stdout, but only be passed as the value of the variable. In fact, if done while the internet is available, the command substitution outputs nothing to the terminal, as expected.
I'm not sure if this is what's causing problems in my script, because I'm running a slightly more elaborate command (out="$(timeout 5 ping google.com | grep -c failure)"
), but my theory is that something weird is happening that messes up later operations with variables and substitutions.
Why is this happening? And why does it only happen when the ping command fails to reach google.com? Thank you for your time.
The output is not going to stdout, it's going to stderr, and is printed to the terminal directly. Use out="$(ping google.com 2>&1)"
to get all the output (stderr and stdout) in your out variable, or consider using exit codes for your command.