2

Command substitution:

var=$(cat /some/file.txt)

assigns output of cat command to var variable (without printing cat command output to console). Next I can print value of var variable:

echo "$var"

But

var=$(java -version)

or

var=$(fish -v)

will immediately print output of the command to console (even without echo command). Why?

Why var variable has no value now?

How can I assign output of the command (e.g. java -version) to variable?

ajanota
  • 108
  • 5

1 Answers1

4

Command substitutions only capture stdout output.

Presumably your commands output to stderr.

Using output redirection, you can capture stderr as well:

var=$(java -version 2>&1) # captures both stdout and stderr
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • I agree that version information should print to _stdout_, but some utilities do it their own way, unfortunately. – mklement0 Feb 26 '16 at 18:49
  • 1
    If your requirements are more complex than this, perhaps see also http://stackoverflow.com/questions/962255/how-to-store-standard-error-in-a-variable-in-a-bash-script – tripleee Mar 14 '16 at 07:56