问题
I am doing command substitution and saving the result to a variable. However, the results of the command contain double quotes and this is causing the variable to be empty.
When running test="$(java -version)"
I get the following result:
openjdk version "1.8.0_65"
OpenJDK Runtime Environment (build 1.8.0_65-b17)
OpenJDK 64-Bit Server VM (build 25.65-b01, mixed mode)
However running echo $test
yields a blank line.
回答1:
The reason that test="$(java -version)"
prints the result to the terminal directly is that java -version
outputs to standard error (stderr), not standard output (stdout).
Because there is no stdout output (which is what $(...)
captures), $test
is assigned an empty string.
The solution is to redirect standard error (stderr) to standard output (stdout).
version=$(java -version 2>&1)
来源:https://stackoverflow.com/questions/41213488/blank-variable-during-bash-command-substitution