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?

1
  • 2
    You have a UUOC (unnecessary use of cat) in var=$(cat /some/file.txt). No need to call cat, simply var=$(</some/file.txt). Commented Feb 26, 2016 at 20:31

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

I agree that version information should print to stdout, but some utilities do it their own way, unfortunately.
If your requirements are more complex than this, perhaps see also stackoverflow.com/questions/962255/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.