TIP: Dealing with Multiple SSH Key Repositories
I have different Git repositories cloned with different SSH keys. Say, one is work code and one is personal / side project.
When I finish work on one repository, and start to work on another and want to fetch the latest changes, I have to switch SSH keys.
That is sometimes annoying as I have to execute following command every time I switch from one repo to another:
ssh-add -D # delete cached key
ssh-add ~/.ssh/my-key # add key I need to use to the ssh-agent
There are some solutions for this, like Configuring SSH
But I found it not so nice solution, although maybe they are fully automated. You have to configure hosts, clone repository with different host, etc. I prefer something else.
Shell aliases for the rescue
I created shell script aliases (in ~/.zshrc
file as I’m using ZSH) that will do commands listed above:
alias sshWork="ssh-add -D; ssh-add ~/.ssh/my-work-key"
alias sshPersonal="ssh-add -D; ssh-add ~/.ssh/my-personal-key"
Now, all I need to do is to execute either sshWork
or sshPersonal
command and it will delete the previously cached key + add a new identity to the authentication agent.
Note: depending on shell you’re using you might need to adjust other shell config file ~/.bashrc
or others. After adjusting config to apply changes without need to logout from terminal just run source ~/.zshrc
or source ~/.bashrc
and it will implement changes in current terminal window.
It’s that simple!