How to Retrieve Hash for Commits in Git
The git log command is used for listing and filtering the project history and searching for particular changes.
You can use git log -1 to show the information about the latest commit and from that information you can use grep to get the hash.
A better method for getting the latest commit’s hash in Git is using the --format option of git log:
git log -n1 --format=format:"%H"
Here, “%H” means “commit hash”.
To get the latest git commit SHA-1 hash ID, use the git-rev-parse command like this:
git rev-parse HEAD or git rev-parse --verify HEAD
In case you want to get only the first 8 digits, use git rev-parse HEAD | cut -c 1-8 where the cut -c 1-8 gives 1 to 8 bytes.
Using the git reflog command is also used if you want to have the history on the head of your branches. With this command, you can find the line referring to the state you want to get back. After getting the hash of the commit you can restore it by using git cherry-pick.
The git log Command
The git log command examines a repository’s history and finds a particular version of a project. Log output can be personalized differently, from filtering commits to displaying them in an entirely user-defined format.
The --format Option
The --format option pretty-prints the contents of the commit logs in a specified format, where <format> can be oneline, short, medium, eference, email, full, fuller, raw, format:<string> and tformat:<string>. When <format> is not specified and has %placeholder, it will act as if --pretty=tformat:<format> were specified.