bash命令替换期间的空白变量 [英] Blank variable during bash command substitution

查看:49
本文介绍了bash命令替换期间的空白变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行命令替换并将结果保存到变量中.但是,命令的结果包含双引号,这导致变量为空.

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命令替换期间的空白变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆