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.
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
I'd highly recommend this over trying to detect the string "fatal: Not a git repository..."
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
You can use:
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 capturingstdout
.