Bash脚本将命令的所有输出分配给变量 [英] Bash scripting assign ALL output from command to variable

查看:66
本文介绍了Bash脚本将命令的所有输出分配给变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从bash脚本中的ping获取成功和失败的响应,但到目前为止还无法完成.

I'm trying to get both successful and unsuccessful responses from a ping in a bash script but am unable to thus far.

我的代码看起来像这样...

My code looks like this...

ping_results=$(ping -c 4 -q google.com)

当ping成功后此方法有效,但是如果我没有Internet连接并且得到了结果

This works when the ping is successful, but if I don't have an internet connection and I get the result

ping: unknown host google.com

它已打印到控制台,并且我的脚本似乎退出了.

It is printed to the console, and my script appears to exit.

我希望将ping结果或错误都存储在ping_results变量中.

I want both the ping result or error to be stored in the ping_results variable.

任何帮助将不胜感激.

推荐答案

好的,对您问题的简单答案是将stderr重定向到stdout.就像Fredik Phil在评论中提到的那样.

Okay, the simple answer to your question is to redirect stderr to stdout. as what Fredik Phil mentioned in the comments.

代替:

ping_results=$(ping -c 4 -q google.com);

使用:

 ping_results=$(ping -c 4 -q google.com 2>&1);

或类似的东西...

但是,根据您的操作,最好测试ping命令的退出代码是1(表示ping以错误结束)还是0(表示ping成功).).退出代码存储在变量"$?"中.

However, depending on what you're doing, it might be better to test if the exit code of the ping command is 1 (indicating that the ping is ending in an error), or 0 (indicating that the ping is successful). the exit code is stored in the variable "$?".

这篇关于Bash脚本将命令的所有输出分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆