Skip to content

Instantly share code, notes, and snippets.

@mpdude
Last active January 14, 2025 04:29
Show Gist options
  • Save mpdude/e56fcae5bc541b95187fa764aafb5e6d to your computer and use it in GitHub Desktop.
Save mpdude/e56fcae5bc541b95187fa764aafb5e6d to your computer and use it in GitHub Desktop.
Wrapper around `ssh` to pick the right one from several GitHub deploy keys
#!/bin/bash
# The last argument is the command to be executed on the remote end, which is something
# like "git-upload-pack 'webfactory/ssh-agent.git'". We need the repo path only, so we
# loop over this last argument to get the last part of if.
for last in ${!#}; do :; done
# Don't use "exec" to run "ssh" below; then the trap won't work.
key_file=$(mktemp -u)
trap "rm -f $key_file" EXIT
eval last=$last
# Try to pick the right key
ssh-add -L | grep --word-regexp --max-count=1 $last > $key_file
ssh -i $key_file "$@"
@fleetingbytes
Copy link

fleetingbytes commented Jan 14, 2025

Thank you very much for this wrapper script. However, for now, I can work without it. Once I created my deploy keys (one per repository) and added each key to its respective github repository (the the repository's settings), and loaded these keys in the ssh agent, I found that github.com will allow me to clone any of my repositories with the first deploy key the agent offers it. Regardless whether that particular key belongs to that repository or any of my other ones. I think that this is a bug and I posted a question in the GitHub community forums about it.

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