ajanota
ajanota

Reputation: 108

Strange behaviour of command substitution in bash

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?

Upvotes: 2

Views: 622

Answers (1)

mklement0
mklement0

Reputation: 440491

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

Upvotes: 4

Related Questions