Bash脚本存储命令输出到变量 [英] Bash script store command output into variable
问题描述
我在将命令的输出存储在bash脚本内的变量中时遇到问题.
我知道通常有两种方法可以做到这一点
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
两个
foo=$(bar)
# or
foo=`bar`
但是对于Java版本查询,这似乎不起作用.
but for the Java version query, this doesn't seem to work.
我做到了:
version=$(java --version)
这不会将值存储在var中.它甚至仍会打印出来,实际上不应该这样.
This doesn't store the value inside the var. It even still prints it, which really shouldn't be the case.
我还尝试将输出重定向到文件,但这也失败了.
I also tried redirecting output to a file but this also fails.
推荐答案
version=$(java -version 2>&1)
版本参数仅需一个破折号,并且如果您重定向stderr(即消息写入的位置),您将获得所需的结果.
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.
作为一个旁注,在类似Unix的系统上,使用两个破折号是一个非正式的标准,但是由于Java试图在不同的平台上实现几乎相同,因此它违反了Unix/Linux的要求,并且在这方面的行为与Windows相同,我怀疑是在Mac OS上.
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.
这篇关于Bash脚本存储命令输出到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!