简体   繁体   English

将命令输出重定向到 bash 中的变量失败

[英]Redirecting command output to a variable in bash fails

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.这会将文件列表写入变量OUTPUT以便稍后读取。 What should i do to make it work?我应该怎么做才能使它工作?

Maybe the output goes to stderr , not stdout ?也许输出到stderr ,而不是stdout Try this:尝试这个:

OUTPUT=$(sudo apache2ctl configtest 2>&1)

For nginx possible situation when configtest can be successful with error in config files.对于 nginx 可能的情况,当 configtest 可以成功但配置文件中出现错误时。 Example:例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM