bash中命令替换的奇怪行为 [英] Strange behaviour of command substitution in bash

查看:45
本文介绍了bash中命令替换的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

命令替换:

var=$(cat /some/file.txt)

将cat命令的输出分配给var变量(不将cat命令的输出打印到控制台).接下来,我可以打印var变量的值:

assigns output of cat command to var variable (without printing cat command output to console). Next I can print value of var variable:

echo "$var"

但是

var=$(java -version)

var=$(fish -v)

将立即将命令的输出打印到控制台(即使没有echo命令).为什么?

will immediately print output of the command to console (even without echo command). Why?

为什么var变量现在没有值?

Why var variable has no value now?

如何将命令的输出(例如java -version)分配给变量?

How can I assign output of the command (e.g. java -version) to variable?

推荐答案

命令替换仅捕获 stdout 输出.

大概您的命令输出到 stderr .

使用输出重定向,您还可以捕获stderr:

Using output redirection, you can capture stderr as well:

var=$(java -version 2>&1) # captures both stdout and stderr

这篇关于bash中命令替换的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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