Bash 脚本将命令输出存储到变量中 [英] Bash script store command output into variable

查看:50
本文介绍了Bash 脚本将命令输出存储到变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将命令的输出存储在 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屋!

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