3

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!

4
  • 4
    What does java -version show when run from the command line? Add MSG=$(java -version 2>&1) and try again. It is probably outputting the information to stderr for some reason. (some distros output that information to stdout, others to stderr.) For example opensuse 13.1 uses stdout, Archlinux uses stderr. (maybe newer versions use stderr) Commented Feb 20, 2016 at 5:52
  • there must be something printed out in stderr and said java not found. Commented Feb 20, 2016 at 5:54
  • While these answers should be correct, on another note, you should really use echo "$MSG" (i.e. quoted) for printing it & for using it otherwise. Commented Feb 20, 2016 at 6:48
  • Yes David, adding 2>&1 worked! Commented Feb 20, 2016 at 8:12

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.