Getting current Git commit version from within Rails app?

A more robust solution would be git show --pretty=%H -q. The -q flag quiets the output.

In order to remove the newline that is part of the output, you can use chomp. For example: system('git show --pretty=%H -q').chomp

The selected answer has the potential to actually return the diff when the commit is not a merge commit. Verified on git version 2.16.2.windows.1.


You can invoke the git command from within your script:

commit = `git show --pretty=%H`
puts commit

Depending on your environment you may want to use the full path to the git binary, and possibly specify the GIT_DIR via an environment variable or --git-dir.


Like @meagar said, use backticks to execute the shell command from within your app, but you may find these two commands more useful:

Full hash:

git rev-parse HEAD

First 7 characters of hash:

git rev-parse --short HEAD