Quick Git trick: Sign your commits after the fact

OK, so this might be a situation you may get into, but I'm blogging this as much for myself as for others because I know this is a situation that I might also head into:

You start working on a new project for a new customer, and you forget to set up PGP signing of your commits in your Git configuration. Now you've pushed your branch, made a pull request but the pull request can not be merged because your commits are not signed. OH NO! Now what?

The one-liner

Luckily, I'm not the only one to do this and a quick search around the web resulted in this post on superuser.com and look, it is actually quite easy. First of all, you configure git to use your PGP key and set the correct email address. Then you use git log to find out the commit hash of the commit before your first commit. Then you use the command:

git rebase --exec 'git commit --amend --no-edit -n -S' -i <commit hash>

Where, obviously, you replace <commit hash> with the actual commit hash.

Simply write and quit the editor coming up describing what the rebase is going to do, and... TADA! All your commits are now signed.

Force push

Yes, you will have to force push your changes to your branch. But since the merging of the pull request was blocked anyway, no one will have pulled your changes. Right? RIGHT?

If anyone pulled your changes before you force pushed, you'll have to warn them and prepare them for a bit of extra work.


And that's it. That's all you need to do to sign your commits after the fact. And next time you start working on a new project, don't forget to configure Git to use your key and sign your commits from the start.