[英]How can I store the result of this command as a variable in my bash script?
I'm building a simple tool that will let me know if a site "siim.ml" resolves. 我正在构建一个简单的工具,它将使我知道网站“ siim.ml”是否可以解析。 If I run the command "ping siim.ml | grep "Name or service not known"" in the linux command line then it only returns text if the site does not resolve.
如果我运行命令“ping siim.ml | grep的‘名称或Linux命令行不知道’,”服务的话,它只有在现场不能解决返回文本。 Any working site returns nothing.
任何工作站点均不返回任何内容。
Using this I want to check if the result of that command is empty, and if it is I want to perform an action. 使用此命令,我想检查该命令的结果是否为空,以及是否要执行操作。
Problem is no matter what I do the variable is empty! 问题是无论我做什么变量都是空的! And it still just prints the result to stdout instead of storing it.
而且它仍然只是将结果打印到stdout而不是存储它。
I've already tried switching between `command` and $(command), and removed the pipe w/ the grep, but it has not worked 我已经尝试过在`command`和$(command)之间切换,并删除了带有grep的管道,但是没有用
#!/bin/bash
result=$(ping siim.ml | grep "Name or service not known")
echo "Result var = " $result
if ["$result" = ""]
then
#siim.ml resolved
#/usr/local/bin/textMe/testSite.sh "siim.ml has resolved"
echo "It would send the text"
fi
When I run the script it prints this: 当我运行脚本时,将输出以下内容:
ping: siim.ml: Name or service not known
Result var =
It would send the text
It's almost certainly because that error is going to standard error rather than standard output (the latter which will be captured by $()
). 几乎可以肯定,因为该错误将导致标准错误,而不是标准输出 (后者将由
$()
捕获)。
You can combine standard error into the output stream as follows: 您可以将标准错误合并到输出流中,如下所示:
result=$(ping siim.ml 2>&1 | grep "Name or service not known")
In addition, you need spaces separating the [
and ]
characters from the expression: 另外,您需要用空格分隔
[
和]
字符与表达式:
if [ "$result" = "" ]
Or even slightly more terse, just check whether ping
succeeds, eg 甚至更简洁,只需检查
ping
是否成功即可,例如
if ping -q -c 1 siim.ml &>/dev/null
then
echo "It would send the text"
## set result or whatever else you need on success here
fi
This produces no output due to the redirection to /dev/null
and succeeds only if a successful ping
of siim.ml
succeeds. 由于重定向到
/dev/null
,因此不会产生任何输出,并且仅在成功对siim.ml
ping
siim.ml
成功时siim.ml
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.