在bash中,将命令输出重定向到一个变量将失败

时间:2021-07-14 15:44:10

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?

将文件列表写入变量输出,以便以后可以读取。我该怎么做才能让它工作呢?

2 个解决方案

#1


30  

maybe the output goes to stderr, not stdout?

也许输出是stderr,而不是stdout?

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

试试这个:OUTPUT=$(sudo apache2ctl configtest 2>&1)

#2


0  

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

#1


30  

maybe the output goes to stderr, not stdout?

也许输出是stderr,而不是stdout?

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

试试这个:OUTPUT=$(sudo apache2ctl configtest 2>&1)

#2


0  

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