Reputation: 409
I am trying to write a bash script, while doing that am stuck here:
I do not understand why this works:
MSG=$(pwd)
echo $MSG
Output:
/home/harsh/source/git/trunk
BUT this does not:
MSG=$(java -version)
echo $MSG
Output:
BLANK
Please help!
Upvotes: 3
Views: 115
Reputation: 47169
Some commands might need 2>&1
at the end to get any output:
MSG=$(java -version 2>&1)
It sends any standard error(2) to wherever standard output(1) is redirected.
Upvotes: 2
Reputation: 7161
Error messages are typically written to the standard error stream stderr
instead of the standard output stream stdout
. If java -version
generates an error instead of what you expected (printing the version), it will likely do so to stderr
. It is also possible that the version information could also printed to stderr
.
The command substitution $()
takes the output from stdout
of what's inside the $()
and substitutes it in its place. In case of an error, this could be nothing. If you are typing this from a terminal, you should still see any output (e.g. error messages) from java
's stderr
in the terminal.
Upvotes: 1