如何将git命令的输出存储在变量中? [英] How do I store the output of a git command in a variable?

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

问题描述

我想要的是将git命令的输出(例如git status)存储在Shell脚本中的变量内.当我说输出时,我说的是终端在执行命令时返回的文本,例如: 在我的回购之外执行git状态:

What I want is to store the output of a git command (such as git status) inside a variable in a shell script. When I say output, I am talking about the text returned in the terminal on execution of a command, for example: on doing a git status outside my repo:

fatal: Not a git repository (or any of the parent directories): .git

我尝试过:

var=$(git status)

但是'var'没有存储任何内容.

But 'var' did not store anything.

推荐答案

您可以使用:

var=$(git status 2>&1)

即将stderr重定向到stdout,然后捕获输出.

i.e. redirect stderr to stdout and then capture the output.

否则,当在stderr上写有错误消息并且您的命令:var=$(git status)仅捕获stdout时.

Otherwise when for error messages are written on stderr and your command: var=$(git status) is only capturing stdout.

这篇关于如何将git命令的输出存储在变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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