问题描述
我正在执行命令替换并将结果保存到变量中.但是,命令的结果包含双引号,这导致变量为空.
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.
运行 test ="$(java -version)"
时,我得到以下结果:
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)
但是运行 echo $ test
会产生空白行.
However running echo $test
yields a blank line.
推荐答案
test ="$(java -version)"
直接将结果打印到终端的原因是 java -version
输出到标准错误(stderr),而不是标准输出(stdout).
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).
因为没有stdout输出(这是 $(...)
捕获的内容),所以为 $ test
分配了一个空字符串.
Because there is no stdout output (which is what $(...)
captures), $test
is assigned an empty string.
解决方案是将标准错误(stderr)重定向到标准输出(stdout).
The solution is to redirect standard error (stderr) to standard output (stdout).
version=$(java -version 2>&1)
这篇关于bash命令替换期间的空白变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!