1

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"* ]]
    then
            echo "It's there!";
    fi

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

cowboysaif
  • 241
  • 2
  • 9

1 Answers1

3

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • A very straightforward answer that works perfectly. So are those stdout and stderr are some kind of streams ? – cowboysaif May 26 '16 at 20:55
  • Yes, stdin, stdout, and stderr are standard streams in Unix-like operating systems - see https://en.wikipedia.org/wiki/Standard_streams – mklement0 May 26 '16 at 20:57