SSH key management with small bash script function
Managing SSH keys for secure access to Git repositories can be a daunting task, especially if you work on multiple accounts hosted on a same platform like Gitlab or Github.
How to use?
If that’s your case, this script maybe for you, just paste it to your ~/.bashrc
or ~/.zshrc
.
I didn’t test with fish
tho.
Then running git-change
to select one SSH for your git project.
function git-change() {
if [ $ZSH_VERSION ]; then
setopt sh_word_split
fi
IFS=$'\n' keys=$(ls -1 ~/.ssh/id_rsa ~/.ssh/*/id_rsa ~/.ssh/id_rsa_* 2> /dev/null)
select item in $keys
do
echo "export GIT_SSH_COMMAND=\"ssh -i $item -o IdentitiesOnly=yes\""
export GIT_SSH_COMMAND="ssh -i $item -o IdentitiesOnly=yes"
break
done
}
How it works?
- This small script list available SSH keys by searching for files named “id_rsa” in ~/.ssh, as well as its subdirectories.
- By default, script searches with this command:
ls -1 ~/.ssh/id_rsa ~/.ssh/*/id_rsa ~/.ssh/id_rsa_*
, feel free to customize it for your use case. - After you select the script,
git-change
function sets theGIT_SSH_COMMAND
environment variable with the appropriate SSH command, including the chosen SSH key.