Skip to content

Instantly share code, notes, and snippets.

@aroder
Forked from mpdude/ssh-deploy-key-wrapper.sh
Last active January 1, 2021 00:37
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 aroder/920d4bf72536f06e6400e5fcfcd9bff6 to your computer and use it in GitHub Desktop.
Save aroder/920d4bf72536f06e6400e5fcfcd9bff6 to your computer and use it in GitHub Desktop.
Wrapper around `ssh` to pick the right one from several GitHub deploy keys
#!/bin/bash
regex_repo_name="\/([^\/]*\.git)"
if [[ ${!#} =~ $regex_repo_name ]]
then
repo_name="${BASH_REMATCH[1]}"
else
echo "Could not find a repo name in ${!#}"
fi
# 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)
# deletes the file anytime an EXIT signal is received (i.e. anytime the script exits)
trap "rm -f $key_file" EXIT
# eval last=$last
eval last=$repo_name
# Try to pick the right key
ssh-add -L | grep --word-regexp --max-count=1 $last > $key_file
ssh -i $key_file "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment