How to save git output to a variable in Bash


April 01, 2020

Some git commands produce output in the terminal, for example, git log shows the details of previous commits. If you’re writing a bash script to automate some build process then you might need to save the output from one of these git commands.

Save git command line output in a variable

To execute git commands in bash you can use env -i and then the git <command>, for example:

1.env -i git log

To capture the output from that command, wrap the full command env -i git log in parenthesis:

1.$(env -i git log)

Finally, set that output to a variable:

1.GIT_LOG= $(env -i git log)

Save last git hash

In a recent project, I had to create a bash variable to store the output of the most recent commit hash. It’s pretty useful if you need to create custom, unique, version names.

1.LAST_GIT_HASH= $(env - i git log --pretty=format:'%h' -n 1)