[英]Bash variable assignment strange behaviour
I am trying to write a bash script, while doing that am stuck here: 我正在尝试编写一个bash脚本,而这样做是困在这里:
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! 请帮忙!
Some commands might need 2>&1
at the end to get any output: 某些命令最后可能需要
2>&1
来获取任何输出:
MSG=$(java -version 2>&1)
It sends any standard error(2) to wherever standard output(1) is redirected. 它将任何标准错误(2)发送到重定向标准输出(1)的任何位置。
Error messages are typically written to the standard error stream stderr
instead of the standard output stream stdout
. 错误消息通常写入标准错误流
stderr
而不是标准输出流stdout
。 If java -version
generates an error instead of what you expected (printing the version), it will likely do so to stderr
. 如果
java -version
生成错误而不是您期望的错误(打印版本),它可能会对stderr
执行此操作。 It is also possible that the version information could also printed to stderr
. 版本信息也可以打印到
stderr
。
The command substitution $()
takes the output from stdout
of what's inside the $()
and substitutes it in its place. 命令替换
$()
接受来自$()
内部的stdout
的输出,并将其替换为它的位置。 In case of an error, this could be nothing. 如果出现错误,这可能不算什么。 If you are typing this from a terminal, you should still see any output (eg error messages) from
java
's stderr
in the terminal. 如果您从终端输入此内容,您仍应该看到终端中
java
的stderr
任何输出(例如错误消息)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.