How to set git user and email per directory

I am using git at several places: at work, at university, and at home. I want an own git user/email for each of those places, but I don't want to care setting the values each time I create or clone a new repository.

Git allows for setting user/email per repository, globally and system-wide, but I need a fourth dimension: per directory. By setting git environment variables using ondir, I managed to get exactly what I need.

  1. Install ondir (on a Mac: brew install ondir, other OSs need to install it from the linked page).

  2. Put these functions into your shell profile (e.g. .profile):

     # ondir configuration
     cd() {
       builtin cd "$@" && eval "`ondir \"$OLDPWD\" \"$PWD\"`"
     }
     pushd() {
       builtin pushd "$@" && eval "`ondir \"$OLDPWD\" \"$PWD\"`"
     }
     popd() {
       builtin popd "$@" && eval "`ondir \"$OLDPWD\" \"$PWD\"`"
     }
     eval "`ondir /`"
    
  3. Configure ondir by putting these lines into ~/.ondirrc (adapt it to whatever you need):

     enter ~/dev/work
       export GIT_AUTHOR_NAME='Name at work'
       export GIT_AUTHOR_EMAIL='email@work.com'
       export GIT_COMMITTER_NAME='Name at work'
       export GIT_COMMITTER_EMAIL='email@work.com'
       echo 'Switched to git user/email settings for "work".'
    
     leave ~/dev/work
       unset GIT_AUTHOR_NAME
       unset GIT_AUTHOR_EMAIL
       unset GIT_COMMITTER_NAME
       unset GIT_COMMITTER_EMAIL
       echo 'Switched back to global git user/email settings.'
    

Now when you cd to ~/dev/work, git config user.name will still show the global git user name, but for commits, the environment variable will be used (check with echo $GIT_AUTHOR_NAME).

Don't forget to source the changed shell profile to your current shell session. Enjoy!

Dominik Schöler Over 10 years ago