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.
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
.
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