1

I know that the construct to capture stdout to a variable is var=$(...). However why does the following not work?

docker pull nginx
version=$(docker run --rm --entrypoint nginx nginx:latest -version)
echo $version

I found, however, adding 2>&1 to the second line above makes things work, ie:

version=$(docker run --rm --entrypoint nginx nginx:latest -version 2>&1)

Can someone help me by explaining why in this case we need to add the additional redirect?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
minh ly
  • 143
  • 2
  • 12
  • 2
    That's because the information is being output to `stderr` (file no `2`). So redirecting `2>&1` redirects `stderr` to `stdout` (file no `1`) which is what is captured by the *Command Substitution* (e.g. the `$(...)`) – David C. Rankin Nov 22 '21 at 19:55
  • That makes sense. I guess I am surprised why the output from that command is output to `stderr`. I don't know how to mark a comment as an answer but I upvoted your comment. Thanks – minh ly Nov 22 '21 at 20:03
  • A lot of utilities output information (version,etc.) to `stderr` so if you are capturing output, you just get the actual program output and not the informational stuff mixed in. – David C. Rankin Nov 22 '21 at 20:07

1 Answers1

0

it is not because of docker. It needs to search for the NGINX side. Looks NGINX version printing argument is not successful sysout. That's why you need to redirect ERROR also to OUTPUT.

NOTE: If you do the below command in the host machine it will be the same problem.

~# nginx -v
nginx version: nginx/1.14.2
~# aa=$(nginx  -v)
nginx version: nginx/1.14.2
~# echo $aa
~#

for Apache, it works fine.

aze2201
  • 453
  • 5
  • 12