Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using GIT_SSH_COMMAND to switch SSH key based on current working directory

I have two Github accounts (work + personal), both with their own SSH keys (key_work & key_personal)

Projects live in:

  • ~/git/work
  • ~/git/personal

I’m trying to set the GIT_SSH_COMMAND up as an environment var such that it looks at the directory the git command is called from, and picks the appropriate ssh key.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So far I’ve tried

.zshrc

export GIT_SSH_COMMAND='~/git-ssh.sh'

~/git-ssh.sh

#!/bin/bash

dir=$(pwd);

if [[ $dir == *"work"* ]]; then
  ssh -i ~/.ssh/key_work -o IdentitiesOnly=yes
elif [[ $dir == *"personal"* ]]; then
  ssh -i ~/.ssh/key_personal -o IdentitiesOnly=yes
else
  exit 1
fi

However when running git clone git@github.com:someorg/repo.git from git/work (or personal) I get

git clone git@github.com:someorg/repo.git
Cloning into 'repo'...
usage: ssh [-46AaCfGgKkMNnqsTtVvXxYa] [-B bind_interface] [-b bind_address]
           [-c cipher_spec] [-D [bind_address:]port] [-E log_file]
           [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file]
           [-J destination] [-L address] [-l login_name] [-m mac_spec]
           [-O ctl_cmd] [-o option] [-P tag] [-p port] [-R address]
           [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]
           destination [command [argument ...]]
       ssh [-Q query_option]
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

The SSH key has access, and worked before I set GIT_SSH_COMMAND, so there must be an issue with my script. Any ideas?

>Solution :

ssh running from your script misses destination (user@host). Git passes a destination as an argument to the script but you’ve forgotten to pass it to ssh. My advice is to pass all arguments from the script to ssh:

ssh -i key "$@"

"$@" means "pass all arguments". See section Special Parameters in man sh.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading