Bash:检查命令的输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43815940/
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
Bash: Check output of command
提问by dev810vm
I need to check the output of apachectl configtest
in a bash script and restart if everything looks good without outputting the command to the screen
我需要检查apachectl configtest
bash 脚本中的输出,如果一切看起来都不错而不将命令输出到屏幕,则重新启动
var =sudo apachectl configtest
If var contains "Syntax OK" then
如果 var 包含“Syntax OK”,则
sudo apachectl graceful
How to do it?
怎么做?
回答by Y. E.
I know this is the old thread and the question doesn't suit this particular site. Anyway, looking for the same question, this page was shown as the first search result. So, I am posting here my final solution, for a reference.
我知道这是旧线程,问题不适合这个特定站点。无论如何,寻找相同的问题,此页面显示为第一个搜索结果。所以,我在这里发布我的最终解决方案,以供参考。
configtestResult=$(sudo apachectl configtest 2>&1)
if [ "$configtestResult" != "Syntax OK" ]; then
echo "apachectl configtest returned the error: $configtestResult";
exit 1;
else
sudo apachectl graceful
fi
This threadcontains a clue regarding catching configtest output.
该线程包含有关捕获 configtest 输出的线索。
回答by Ville Oikarinen
The bash syntax you are after in your first command is probably "command substitution":
您在第一个命令中使用的 bash 语法可能是“命令替换”:
VAR=$(sudo apachectl configtest)
VAR=$(sudo apachectl configtest)
VAR will contain the output of the commandline.
VAR 将包含命令行的输出。
But, if you just want to know if the output contains "Syntax OK", do it like this:
但是,如果您只想知道输出是否包含“Syntax OK”,请这样做:
sudo apachectl configtest | grep -q "Syntax OK" && proceed || handle-error
sudo apachectl configtest | grep -q "Syntax OK" && proceed || handle-error
where proceed
and handle-error
are your functions that handle your ok and error cases, respectively.
你的函数在哪里proceed
和handle-error
分别处理你的 ok 和 error 情况。
(Note the -q option of grep to hide the output of the apachectl command.)
(注意 grep 的 -q 选项来隐藏 apachectl 命令的输出。)
回答by berrytchaks
As @slm says on the link, you can used -q for quiet. That way it don't output the command on the screen. Make sure there no space between the variable, the '=' and the command as @William Pursell says here. After that test if your variable contains "Syntax OK". The following code snippet does that.
正如@slm 在链接上所说,您可以使用 -q 来保持安静。这样它就不会在屏幕上输出命令。确保变量、'=' 和@William Pursell在这里所说的命令之间没有空格。之后测试您的变量是否包含“语法正常”。下面的代码片段就是这样做的。
var1=$(sudo apachectl configtest)
if echo $var1 | grep -q "Syntax OK"; then
sudo apachectl graceful
fi