cowboysaif cowboysaif - 8 months ago 36
Linux Question

Output of a command not passing to assigned variable

I was trying to test nginx config in a script:

reply="$(nginx -t)"
echo $reply

But $reply is not containing the returned text. If i put first line in a terminal, nginx texts are popping in the terminal, but if i put second line in terminal, nothing outputs.
My interest is to use that nginx test's output in a if statement

reply="$(nginx -t)"
if [[ ${reply} == *"nginx: configuration file /etc/nginx/nginx.conf test failed"* ]]
echo "It's there!";

Is there any way to get the output returned by the command nginx -t in the variable ?


Judging by your conditional you're testing for an error message, which means that nginx most likely printed that to stderr, whereas $(...) only captures stdout output by default.

In order to capture both streams, use:

reply="$(nginx -t 2>&1)"

2>&1 redirects stderr to stdout, so that stderr is also captured by $(...), the command substitution.