Skip to content

Instantly share code, notes, and snippets.

@rohit267
Created April 12, 2023 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rohit267/e0ab4a4d8d00ccc5fbd035ee1808bf7d to your computer and use it in GitHub Desktop.
Save rohit267/e0ab4a4d8d00ccc5fbd035ee1808bf7d to your computer and use it in GitHub Desktop.
Use multiple github accounts with ssh keys using bash script
# Add these lines to your .bashrc or .zshrc
function checkIfWorkDir(){
if [[ $PWD == *"rohitmahto/work"* ]]; then
echo "Work flder found."
git config user.name rohit-work
git config user.email rohit.mahto@work.com
echo "Git user name and email set to work account."
else
echo "Using Global Git Config."
fi
}
function cd(){
builtin cd "$@" && checkIfWorkDir
}
checkIfWorkDir
@rohit267
Copy link
Author

I will assume you have set up ssh keys. If not use this link: https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

The problem:

Even if I have separate ssh keys to different GitHub accounts, git was using global account to push/commit changes to a repo if the local git config was not set.

The solution is to use set default/personal account for every-thing else other than work folders.

The Idea:

Set the corresponding work account to local git config if current directory is a work folder else use the personal/default account.

Explanation:

The method checkIfWorkDir () checks if the current folder contains your work folder. If yes it sets the local git config to your work account else does nothing means git will use your global git config.

The method cd() is basically an alias to cd command and runs the checkIfWorkDir() method every-time you cd into any folder.

Bug:

It will show throw a Not a git repository error when you are not in a directory which is a git repo. You can ignore it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment