Working with multiple git identities with envrc

The canonical way to work with multiple git identities on the same computer is to specify different ssh hosts by modifying the home ssh config and each local git remote urls (see https://superuser.com/questions/232373/how-to-tell-git-which-private-key-to-use ).

But sometimes we want to achieve the same effect without modifying the ssh config, nor the git remote urls. Here is how to do so with envrc.

direnv bash plugin to achieve this selection depending on the working directory

direnv( https://direnv.net/ ) is a bash plugin that temporarily overrides environment variables when entering and exiting a specified directory. You can override git settings using environment variables, and also dictate a specific ssh identity using this .envrc file:

# settings for committing
export GIT_AUTHOR_NAME='example'
export GIT_AUTHOR_EMAIL='example@mail.com'
export GIT_COMMITTER_NAME='example'
export GIT_COMMITTER_EMAIL='example@mail.com'

# ssh setting for choosing one specific identity only
export GIT_SSH_COMMAND="ssh -o IdentitiesOnly=yes -i ~/.ssh/id_ed25519_example -F /dev/null"

# optional: ensures that the specified identity is available in ssh-agent
ssh-add -l | grep example || ssh-add ~/.ssh/id_ed25519_example

Leave a Comment