How do I store the output of a git command in a va

2019-04-03 08:11发布

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

I tried this:

var=$(git status)

But 'var' did not store anything.

标签: linux bash shell
2条回答
乱世女痞
2楼-- · 2019-04-03 08:35

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

  • 128 for this case
  • 0 if no errors.

I'd highly recommend this over trying to detect the string "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.

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

查看更多
3楼-- · 2019-04-03 08:43

You can use:

var=$(git status 2>&1)

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

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

查看更多
登录 后发表回答