Blank variable during bash command substitution

微笑、不失礼 提交于 2021-02-13 17:04:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!