Linux 将命令输出重定向到 bash 中的变量失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10319745/
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
Redirecting command output to a variable in bash fails
提问by roman
I'm trying to redirect command output to a variable:
我正在尝试将命令输出重定向到一个变量:
OUTPUT=$(sudo apache2ctl configtest)
and then to read it:
然后阅读它:
echo $OUTPUT
When running it the output is the following:
运行时输出如下:
19:19:12 user@user ~ OUTPUT=$(sudo apache2ctl configtest)
Syntax OK
Syntax OK
But the variable stays blank. I've tried the same for other commands and everything works fine.
但变量保持空白。我已经对其他命令尝试了相同的方法,一切正常。
OUTPUT=$(ls -l)
This writes file list to variable OUTPUT
so that it can be read later.
What should i do to make it work?
这会将文件列表写入变量,OUTPUT
以便稍后读取。我应该怎么做才能使它工作?
采纳答案by johnshen64
maybe the output goes to stderr
, not stdout
?
也许输出去stderr
,不是stdout
?
try this: OUTPUT=$(sudo apache2ctl configtest 2>&1)
尝试这个: OUTPUT=$(sudo apache2ctl configtest 2>&1)
回答by beliy
For nginx possible situation when configtest can be successful with error in config files. Example:
对于 nginx 可能的情况,当 configtest 可以成功但配置文件中出现错误时。例子:
nginx: [warn] conflicting server name "test.com" on 0.0.0.0:80, ignored
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
for correct check errors in bash scripts need use:
为了正确检查 bash 脚本中的错误,需要使用:
if [[ $((sudo /sbin/service nginx configtest) 2>&1 | grep "failed\|warn" ) ]]; then
echo "ERROR!!!"
else
echo "OK!!!"
fi