bash 如何将 git 命令的输出存储在变量中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28186162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I store the output of a git command in a variable?
提问by aliasav
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 status)的输出存储在 shell 脚本中的变量中。当我说输出时,我指的是在执行命令时在终端中返回的文本,例如:在我的 repo 之外执行 git status 时:
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' 没有存储任何东西。
回答by anubhava
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
.
否则,当 for 错误消息被写入stderr
并且您的命令:var=$(git status)
仅捕获stdout
.
回答by Adam
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
- 0 if no errors.
- 128 对于这种情况
- 0 如果没有错误。
I'd highly recommend this over trying to detect the string "fatal: Not a git repository..."
我强烈推荐这个尝试检测字符串“fatal: Not a git repository ...”
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 status --porcelain 和 --short 对脚本很有用。
If you're using Linux/OS X etc the full details are at man git-status
如果你使用的是 Linux/OS X 等,完整的细节在man git-status