Have you ever wondered how to manage two or more Github accounts on your machine?

If so, that must be something for you.

Project specific git author

Let’s assume we want to manage James Bond’s accounts with following emails:

We can configure an alias for second account by running:

1
$ git config --global alias.workprofile 'config user.email "james@work.dev"'

Behind the scene, it adds additional alias in ~/.gitconfig:

1
2
[alias]
workprofile = config user.email \"james@work.dev\"\n

After cloning repo, first thing we have to remember to do is running:

1
$ git workprofile

It simply configures the project to use workprofile’s email, by writing into .git/config in the repository following setting:

1
2
[user]
email = james@work.dev

Now Git sets the author of new commits accordingly. Cool!

Change author in commits history

Supposing that we have project with commits already messed up regarding author, happily they can be filtered and author can be changed, using following command:

1
$ git filter-branch --commit-filter 'if [ "$GIT_AUTHOR_NAME" = "James Bond" ]; then export GIT_AUTHOR_NAME="James Bond"; export GIT_AUTHOR_EMAIL=james@work.dev; fi; git commit-tree "$@"'

Then we have to push changes with force option:

1
$ git push -f origin branch_name

Unfortunetelly, that’s not all. If we are using Github, we will most likely see something annoying. Commits would be marked with two avatars, and we would see something like “user a” committed with “user b”.
So, we should also take care of setting committer name similarly as we did before.

That could be achieved by:

1
$ git filter-branch --commit-filter 'if [ "$GIT_COMMITTER_NAME" = "James Bond" ]; then export GIT_COMMITTER_NAME="James Bond"; export GIT_COMMITTER_EMAIL=james@work.dev; fi; git commit-tree "$@"'

These commands are quite difficult to remember though, so I would suggest to put them into your ~/.aliases:

For example:

1
alias authorwork='git filter-branch --commit-filter '"'"'if [ "$GIT_AUTHOR_NAME" = "James Bond" ]; then export GIT_AUTHOR_NAME="James Bond"; export GIT_AUTHOR_EMAIL=james@work.dev; fi; git commit-tree "$@"'"'"''
  • Here small trick will be necessary to make it work - we need to wrap ‘ character into ‘“ “‘.

That’s all!