1

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.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Michele
  • 25
  • 6

1 Answers1

3

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.

WayToDoor
  • 1,180
  • 9
  • 24
  • 1
    Thanks to your reply, I've decided to research bash redirecting, and I've read that ```&>``` (or ```>&``` for that matter) has the effect of redirecting both standard output and standard error. Does that mean that I can also ```out="$(ping google.com &>1 | grep -c failure)"```? Also, why is the syntax necessarily ```2>&1```, and not just ```2>1```? I'm reading the Bash Reference Manual, chapter 3.6 but it's not very clear – Michele Feb 24 '22 at 14:50
  • 1
    You might want to read answers here (https://stackoverflow.com/questions/818255/in-the-shell-what-does-21-mean) for more information about stream redirection. – WayToDoor Feb 24 '22 at 15:06