Making Git prompt for SSH username

In what seems to be an unusual configuration—as I was unable to find any information on how to do it—I had a need to make Git prompt for an SSH username. The repositories in question are on a shared computer, but the host for the remote copies requires individual user authentication using a password and a TOTP code. A crude solution was to set GIT_SSH_COMMAND='ssh -l $USER', but this requires the user to remember to run, e.g., USER=username git pull, although this can be helped by setting USER='Prefix_git_with_"USER=yourusername"!!!!!!!!' in .bashrc. After much trial and error, I arrived at the solution of setting the GIT_SSH environment variable in .bashrc to point at the following shell script:

#!/bin/bash
# Make Git prompt for SSH username
# M. Petroff, 2024-12
if [[ $1 = "-G" ]]
then
  # Handle Git's SSH variant test
  ssh "$@"
else
  # Prompt for username
  read -p "Username: " user </dev/tty
  ssh -l "$user" "$@"
fi

There are two peculiarities here to keep in mind. First, stdin and stdout cannot be used, so input redirection needs to be used with read to get input directly from the terminal (/dev/tty), similar to what SSH itself does; with the -p flag, read writes to stderr, which is okay. With this resolved, there were mysterious issues with either the username prompt being displayed twice or with needing to press “enter” to see the prompt, depending on the exact details of the then work-in-progress script. I eventually realized this was due to Git’s SSH variant checking, which first calls the GIT_SSH command with the -G argument to figure out which variant of SSH is in use. While this check can be avoided by setting GIT_SSH_VARIANT explicitly, it was easy enough to handle the check in the shell script.

This entry was posted in and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *