Skip to content

Instantly share code, notes, and snippets.

@chsxf
Last active July 5, 2022 10:56
Show Gist options
  • Save chsxf/7f7ca32bf436d8f9f0fe35e2bb9d1b63 to your computer and use it in GitHub Desktop.
Save chsxf/7f7ca32bf436d8f9f0fe35e2bb9d1b63 to your computer and use it in GitHub Desktop.
Setup SSH config for an existing repository
#!/bin/bash
# Color ANSI escape codes:
# https://stackoverflow.com/a/5947802
WHITE="\033[1;37m"
RED="\033[0;31m"
RESET_COLOR="\033[0m"
if [ $# -ne 0 ]; then
echo -e "${RED}Invalid argument count${RESET_COLOR}\n"
echo "Usage:"
echo -e "\tgsetsshcfg"
exit 1
fi
GIT_URI=$1
echo -e "${WHITE}Please answer those questions in order to add another remote to your repository with SSH"
CWD=`pwd`
cd ~/.ssh
KEYS=`ls -1 *.pub`
cd "${CWD}"
COUNTER=0
echo "Select the SSH to use with your repository:"
for entry in $KEYS
do
[[ $entry =~ ^(.+)\.pub$ ]];
((COUNTER=COUNTER+1))
echo -e "\t$COUNTER. ${BASH_REMATCH[1]}"
done
read -p "Key #: " KEY_INDEX
if [[ $KEY_INDEX =~ ^[1-9]\d*$ && $KEY_INDEX -le $COUNTER ]]; then
((SELECTED_INDEX=$KEY_INDEX-1))
ARR=($KEYS)
[[ ${ARR[$SELECTED_INDEX]} =~ ^(.+)\.pub$ ]];
SELECTED_KEY=${BASH_REMATCH[1]}
echo -e "${WHITE}Selected key: ${SELECTED_KEY}${RESET_COLOR}"
else
echo -e "${RED}Invalid key${RESET_COLOR}"
exit 2
fi
echo ""
echo -e "${WHITE}Setting SSH config in ..."
for i in {5..1}
do
echo $i
sleep 1
done
echo -e "${RESET_COLOR}"
if [[ -z $GIT_REMOTE ]]; then
NEW_GIT_REMOTE=$DEFAULT_REMOTE
else
NEW_GIT_REMOTE=$GIT_REMOTE
fi
CORESSH_COMMAND="ssh -i ~/.ssh/${SELECTED_KEY} -F /dev/null"
git config --local core.sshCommand "${CORESSH_COMMAND}"

Purpose

This script is useful when you have multiple SSH keys on your system, eventually having several SSH keys tied to different accounts for the same domain.

It makes use of the core.sshCommand git configuration directive to assign a specific SSH key to a repository.

Requirements

The script will look for SSH keys in ~/.ssh

You'll also need bash and git installed on your system.

Installation

From the Terminal, move to the directory you want to install this script (I recommend a directory with your $PATH environment variable) and execute those commands:

wget https://gist.github.com/chsxf/7f7ca32bf436d8f9f0fe35e2bb9d1b63/raw/gsetsshcfg
chmod +x gsetsshcfg

Usage

gsetsshcfg

The script will then guide you through the process.

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