Bash 脚本将命令输出存储到变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9768228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash script store command output into variable
提问by user1278282
I have a problem concerning storing the output of a command inside a variable within a bash script.
I know in general there are two ways to do this
我有一个关于将命令的输出存储在 bash 脚本中的变量中的问题。
我知道一般有两种方法可以做到这一点
either
任何一个
foo=$(bar)
# or
foo=`bar`
but for the Java version query, this doesn't seem to work.
但是对于 Java 版本查询,这似乎不起作用。
I did:
我做了:
version=$(java --version)
This doesn't store the value inside the var. It even still prints it, which really shouldn't be the case.
这不会将值存储在 var 中。它甚至仍然打印它,这真的不应该是这种情况。
I also tried redirecting output to a file but this also fails.
我也尝试将输出重定向到文件,但这也失败了。
回答by user unknown
version=$(java -version 2>&1)
The version param only takes one dash, and if you redirect stderr, which is, where the message is written to, you'll get the desired result.
version 参数只需要一个破折号,如果您重定向 stderr,即消息写入的位置,您将获得所需的结果。
As a sidenote, using two dashes is an inofficial standard on Unix like systems, but since Java tries to be almost identical over different platforms, it violates the Unix/Linux-expectations and behaves the same in this regard as on windows, and as I suspect, on Mac OS.
作为旁注,在类 Unix 系统上使用两个破折号是非官方标准,但是由于 Java 试图在不同平台上几乎相同,因此它违反了 Unix/Linux 期望并且在这方面的行为与在 Windows 上相同,并且正如我怀疑,在 Mac OS 上。
回答by Eran Ben-Natan
That is because java -version
writes to stderr
and not stdout
. You should use:
那是因为java -version
写入stderr
而不是stdout
. 你应该使用:
version=$(java -version 2>&1)
In order to redirect stderr
to stdout
.
为了重定向stderr
到stdout
.
You can see it by running the following 2 commands:
您可以通过运行以下 2 个命令来查看它:
java -version > /dev/null
java -version 2> /dev/null