Use an Alternate SSH Key with Git
By default, Git uses the primary ssh key loaded in ssh-agent (or the default ~/.ssh/id_rsa / id_ed25519). There’s no built-in fallback mechanism — if the first key fails, Git doesn’t try alternates. Three approaches force a specific key on a per-command or per-repository basis.
Via ssh-agent (one-off commands)
ssh-agent bash -c "ssh-add $KEY_FILE && git $COMMAND"This spawns a temporary agent, adds the key, runs the command, and discards the agent. Limitation: does not work with GPG authentication subkeys.
$KEY_FILEmust be the full path to a private key file (e.g.,~/.ssh/id_rsa).
Via GIT_SSH_COMMAND environment variable
GIT_SSH_COMMAND="ssh -i $KEY_FILE -F /dev/null -o IdentityAgent=none" git $COMMAND-i $KEY_FILE— use this specific key-F /dev/null— ignore~/.ssh/config(prevents unexpected overrides)-o IdentityAgent=none— ignore ssh-agent (prevents agent keys from taking precedence)
When using a GPG authentication subkey or KeePassXC (referenced by public key), the IdentityAgent=none flag is unnecessary:
GIT_SSH_COMMAND="ssh -i $KEY_FILE -F /dev/null" git $COMMANDVia core.sshCommand config (persistent, per-repo)
git config core.sshCommand "ssh -i $KEY_FILE -F /dev/null -o IdentityAgent=none"This persists in the repository’s .git/config and applies to all subsequent operations. Useful for ongoing work with a specific key on a specific repo. See git-on-windows-sshcommand for the Windows-specific quoting rules around this same option.
Sources
Related: ssh, gpg-key-with-ssh-support, git-on-windows-sshcommand