Search code examples
linuxbashssh-agent

How does the command 'ssh-agent /bin/bash' start a new shell with the agent's environment variables set?


I am just trying to better understand running ssh-agent. Below are three samples of how I have run ssh-agent. Note that for each example I close my session, and then start out with a fresh bash shell. In each new shell I confirm that ssh-agent is not running. I'm running bash shell (on Ubuntu/WSL). Question after the code samples.

If I want to start ssh-agent in the current shell, I can run the agent, and then manually set the environment variables that the agent returns.

$ ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-grVAkSC9cY98/agent.18454; export SSH_AUTH_SOCK;
SSH_AGENT_PID=18455; export SSH_AGENT_PID;
echo Agent pid 18455;
$ SSH_AUTH_SOCK=/tmp/ssh-grVAkSC9cY98/agent.18454
$ export SSH_AUTH_SOCK
$ SSH_AGENT_PID=18455
$ export SSH_AGENT_PID
$ ssh-add
Enter passphrase for /home/username/.ssh/id_rsa:
Identity added: /home/username/.ssh/id_rsa (/home/username/.ssh/id_rsa)
$ echo $SHLVL
1

More easily I can just use eval

$ eval $(ssh-agent)
Agent pid 18478
$ ssh-add
Enter passphrase for /home/username/.ssh/id_rsa:
Identity added: /home/username/.ssh/id_rsa (/home/username/.ssh/id_rsa)
$ echo $SHLVL
1

If I want to start ssh-agent in a new shell I can run ssh-agent /bin/bash rather than starting the shell, and then repeating the previous command (I know that the new shell can inherent ssh-agent from the parent shell, but I'm just interested in understanding what is going on with this command)

$ ssh-agent /bin/bash
$ ssh-add
Enter passphrase for /home/username/.ssh/id_rsa:
Identity added: /home/username/.ssh/id_rsa (/home/username/.ssh/id_rsa)
$ echo $SHLVL
2

Now the question: It seems like the command ssh-agent does not set the environment variables, but only returns them as a command string that must be evaluated (I'm curious as to why it works this way). How does the command (or two commands on the same line) ssh-agent /bin/bash start the new shell with the environment variables set?


Solution

  • In general, ssh-agent can run any command in an environment where SSH_AUTH_SOCK and SSH_AGENT_PID are available. ssh-agent /bin/bash is just the special case where that command happens to be a shell.

    With no argument, it simply outputs code suitable for use with eval to create the same environment, rather than starting a new process with that environment.