Bash - 命令替换 $(ping google.com) 输出到终端
我一直在编写一个脚本,其奇怪的行为让我发疯,但我设法找到了可能的问题所在:像这样的命令替换
out="$(ping google.com)"
如果在互联网不可用时完成,则将其输出到终端
ping: google.com: 名称解析暂时失败
即使根据我的理解,被替换的命令是在子 shell 中运行的,所以命令的输出应该不转到标准输出,而仅作为变量的值传递。事实上,如果在互联网可用时完成,命令替换将不会像预期的那样向终端输出任何内容。
我不确定这是否是导致我的脚本出现问题的原因,因为我正在运行一个稍微复杂一些的命令 (out="$(timeout 5 ping google.com | grep -c failure)"
),但我的理论是,正在发生一些奇怪的事情,它会扰乱后续的变量和替换操作。
为什么会发生这种情况?为什么只有当 ping 命令无法到达 google.com 时才会发生这种情况?感谢您抽出时间。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
输出不会发送到 stdout,而是发送到 stderr,并直接打印到终端。使用
out="$(ping google.com 2>&1)"
获取 out 变量中的所有输出(stderr 和 stdout),或者考虑对命令使用退出代码。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.