Sample Header Ad - 728x90

WSL2 Ubuntu: How to start ssh-agent and add ssh key automatically on each terminal start up

3 votes
1 answer
13599 views
I'm using WSL2, on Terminal, with Ubuntu installed. I have added the following to my .bashrc:
# Start ssh-agent
# check if ssh-agent is already running
if [ -z "$SSH_AUTH_SOCK" ]; then
     #start ssh-agent
    eval "$(ssh-agent -s)"
fi


# Ask for ssh-add
read -p "Do you want to add your SSH public key? (y/n) " response

if [ "$response" = "y" ]; then
  ssh-add ~/id_rsa
  ssh-add -l
elif [ "$response" = "n" ]; then
  echo "No identity on terminal session"
else
  echo "Invalid response"
fi
With the idea that every time I open a new terminal, it will ask for a prompt if an identity is needed and proceed to start ssh-agent and add the key if yes. At first, it appears as if the script work and it'll show the agent's PID, along with a prompt for my ssh password and I'm able to see the ssh-agent when i do top. However, it did not actually initialize ssh-agent nor add the key, despite seeing the output of these commands. I even did ssh-add -l and it'll output: The agent has no identities. How do I go about making this work? This has to be a WSL issue..
Asked by Nik Shafiq Sirhan (31 rep)
Mar 22, 2023, 05:51 AM
Last activity: Apr 16, 2025, 11:10 AM