40

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.

2
  • 1
    The example output probably went to STDERR, and var will contain what was sent to STDOUT. You could use 2>&1 to redirect the former to the latter. Commented Jan 28, 2015 at 6:45
  • Thanks, the output in fact went to STDERR. Commented Jan 28, 2015 at 6:51

2 Answers 2

69

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! Could you please provide any doc links I could study. (I'd give you an vote-up but my low repo won't allow it.)
3

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

2 Comments

Thanks, this method using exit codes is what I needed exactly.
How do I check whether a git command supports exit code or not? Because I am trying to use this approach to solve similar problem. but the command is git worktree remove. When I store the exit code of this command in a shell variable and print, there is nothing that is getting printed - stackoverflow.com/q/68409420/5347487

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.