如何在变量中存储git命令的输出?

时间:2022-12-27 15:46:13

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:

我想要的是将git命令的输出(例如git状态)存储在shell脚本中的变量中。当我说output时,我指的是在执行命令时在终端中返回的文本,例如:在repo之外执行git状态:

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

I tried this:

我试着这样的:

var=$(git status)

But 'var' did not store anything.

但“var”没有存储任何内容。

2 个解决方案

#1


22  

You can use:

您可以使用:

var=$(git status 2>&1)

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

例如,将stderr重定向到stdout,然后捕获输出。

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

否则,当错误消息写入stderr时,您的命令:var=$(git状态)只捕获stdout。

#2


1  

That message comes out on standard error, by default $(cmd) only captures standard out. You can fix by redirecting standard error to standard out - see one of the other answers. However you could use the exit code instead

这个消息是在标准错误上发出的,默认$(cmd)只捕获标准输出。您可以通过将标准错误重定向到标准输出来修复—请参阅其他答案中的一个。但是您可以使用退出代码

  • 128 for this case
  • 128年对于这种情况
  • 0 if no errors.
  • 如果没有错误。

I'd highly recommend this over trying to detect the string "fatal: Not a git repository..."

我强烈建议您不要尝试检测字符串“致命:不是git存储库……”

foo=$(git status)
fatal: Not a git repository (or any of the parent directories): .git
echo $?
128

Additionally there is a git status --porcelain and --short which are useful for scripting.

此外,还有一个git状态—porcelain和—short对于脚本来说很有用。

If you're using Linux/OS X etc the full details are at man git-status

如果您正在使用Linux/OS X等,详细信息将在man git-status中

#1


22  

You can use:

您可以使用:

var=$(git status 2>&1)

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

例如,将stderr重定向到stdout,然后捕获输出。

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

否则,当错误消息写入stderr时,您的命令:var=$(git状态)只捕获stdout。

#2


1  

That message comes out on standard error, by default $(cmd) only captures standard out. You can fix by redirecting standard error to standard out - see one of the other answers. However you could use the exit code instead

这个消息是在标准错误上发出的,默认$(cmd)只捕获标准输出。您可以通过将标准错误重定向到标准输出来修复—请参阅其他答案中的一个。但是您可以使用退出代码

  • 128 for this case
  • 128年对于这种情况
  • 0 if no errors.
  • 如果没有错误。

I'd highly recommend this over trying to detect the string "fatal: Not a git repository..."

我强烈建议您不要尝试检测字符串“致命:不是git存储库……”

foo=$(git status)
fatal: Not a git repository (or any of the parent directories): .git
echo $?
128

Additionally there is a git status --porcelain and --short which are useful for scripting.

此外,还有一个git状态—porcelain和—short对于脚本来说很有用。

If you're using Linux/OS X etc the full details are at man git-status

如果您正在使用Linux/OS X等,详细信息将在man git-status中