bash 将命令输出保存到变量而不打印到标准输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17603823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save command output to variable without it printing to standard output
提问by Filip Haglund
I'm doing a bash script and I'm grabbing the output from this command:
我正在做一个 bash 脚本,我正在从这个命令中获取输出:
fpings=$(fping -c 1 -t 1 $ips | sort)
The fpingsvariable does contain the output from the command, and the actual output of the command is not printed to the shell, but it still writes a line to the shell for each ip pinged.
该fpings变量确实包含命令的输出,并且命令的实际输出不会打印到 shell,但它仍然会为每个 ping 的 ip 向 shell 写入一行。
There is a switch (-q) to suppress the output (the part that I want) but not any to suppress the part I don't want.
有一个开关 ( -q) 可以抑制输出(我想要的部分),但没有任何可以抑制我不想要的部分。
How do I get the result from the fpings command without it printing stuff to the shell?
如何从 fpings 命令获取结果而不将内容打印到 shell?
回答by choroba
If you do not want to see the standard error, redirect it to /dev/null:
如果您不想看到标准错误,请将其重定向到/dev/null:
fpings=$(fping -c 1 -t 1 $ips 2>/dev/null | sort)
回答by exussum
fpings=$( {fping -c 1 -t 1 $ips | sort; } 2>&1 )
should work the {} capture everything and then it redirects both streams (out and err) to just out and saves in the variable
应该工作 {} 捕获所有内容,然后将两个流(输出和错误)重定向到刚刚输出并保存在变量中

