In Bash, you can use the git log
command along with some text manipulation tools to extract the "second to last" or "third to last" commit hash and then copy it to your clipboard. Here's how you can do it:
To copy the "second to last" commit hash to your clipboard:
git log --format=%H | sed -n '2p' | clip
To copy the "third to last" commit hash to your clipboard:
git log --format=%H | sed -n '3p' | clip
Let's break down each command:
git log --format=%H
: This command retrieves the commit hashes of all commits in the repository, using the %H
format specifier to get only the hash.sed -n '2p'
: This command uses the sed
(stream editor) utility to extract the specified line from the output. The n
option suppresses automatic printing of lines, and '2p'
tells sed
to print the second line.clip
: Copied output from pipe into clipboard (Windows)
pbcopy
: This command is used on macOS to copy the input to the clipboard (instead of clip
)You can replace 2
with 3
in the above commands to get the "third to last" commit hash.
Now, let's walk through an example:
Suppose you have a Git repository with the following commit history:
commit a1b2c3d (latest commit)
commit e4f5g6h
commit i7j8k9l
commit m0n1o2p (oldest commit)
If you run the "second to last" commit hash command:
git log --format=%H | sed -n '2p' | pbcopy
The output will be e4f5g6h
, which is the hash of the second-to-last commit. This hash will be copied to your clipboard.
Feel free to adapt the commands to your specific use case or operating system if needed.