Created
April 12, 2023 18:06
-
-
Save rohit267/e0ab4a4d8d00ccc5fbd035ee1808bf7d to your computer and use it in GitHub Desktop.
Use multiple github accounts with ssh keys using bash script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 [email protected] | |
echo "Git user name and email set to work account." | |
else | |
echo "Using Global Git Config." | |
fi | |
} | |
function cd(){ | |
builtin cd "$@" && checkIfWorkDir | |
} | |
checkIfWorkDir |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 tocd
command and runs thecheckIfWorkDir()
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.