Set commit signing per git repository

olistik profile image olistik Updated on ・2 min read

When dealing with multiple git identities it's sometimes useful to perform a custom setup for commit signing, for each repository:

λ gpg --list-keys my@email.com
pub   dsa3072 2016-06-23 [SC]
uid           [ unknown] olistik <my@email.com>
sub   elg3072 2016-06-23 [E]

It is also possible to extract the the value with a bit of scripting (Ruby in this case):

λ gpg --list-keys --fingerprint --with-colons my@email.com | ruby -e "puts STDIN.read.lines.grep(/^fpr/)[0].match(/^.*:([0-9A-Z]+):.*/)[1]"

And then update the git settings within the repository's directory:

λ git config user.signingkey XXYYZZ
λ git config commit.gpgsign true
λ git config user.email "my@email.com"
λ git config user.name "olistik"

Here's a convenience script that can be invoked to setup commit signing:


set -e

GPG_KEY=$(gpg --list-keys --fingerprint --with-colons my@email.com | ruby -e "puts STDIN.read.lines.grep(/^fpr/)[0].match(/^.*:([0-9A-Z]+):.*/)[1]")
git config user.signingkey $GPG_KEY
git config commit.gpgsign true
git config user.email "my@email.com"
git config user.name "olistik"

Here are the versions of my environment:

λ ruby -v
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin18]
λ gpg --version
gpg (GnuPG) 2.2.17
λ git --version
git version 2.20.1 (Apple Git-117)

Issues when committing

If you encounter the following error after a commit command:

error: gpg failed to sign the data
fatal: failed to write commit object

You could try to update the GPG_TTY environment variable and re-run the commit command:

λ export GPG_TTY=$(tty)

It it succeeds, then you can persist this change by putting this line into your .zshrc (or .bashrc according to the shell you are using).

Posted on by:


Editor guide