0

What am I not understanding?

I run ssh-agent and it appears to set some environment variables but when I echo them, I don't get back what I expect.

❯ ssh-agent
SSH_AUTH_SOCK=/var/folders/pn/b_2jl_j55kl504pvctj2jw2c0000gn/T//ssh-SGC2u3LSE0Gu/agent.6521; export SSH_AUTH_SOCK;
SSH_AGENT_PID=6522; export SSH_AGENT_PID;
echo Agent pid 6522;

~
❯ echo $SSH_AGENT_PID


~
❯ echo $SSH_AUTH_SOCK
/private/tmp/com.apple.launchd.lfH6wkqh4H/Listeners
skube
  • 241
  • 3
  • 6
  • 2
    Note despite the fact you did not manage to set the variables, the process with PID 6522 is running and listening on the socket. You may want to `kill` it manually. – Kamil Maciorowski Aug 01 '22 at 17:05

1 Answers1

3

ssh-agent is a separate executable. It can neither set nor change variables and the environment of your shell. Without a debugger, only the shell itself can do this (compare this answer).

Therefore ssh-agent generates shell code for a shell to evaluate. You actually saw the code printed to your console, but not evaluated. The right way to start a new ssh-agent and set variables is:

eval "$(ssh-agent)"

Notes:

  • Manuals and how-tos usually use

     eval `ssh-agent`
    

    because it's a universal syntax that should work in many shells, no matter if sh-like or csh-like. The command with "$(…)" follows modern good practices in sh-like shells and your zsh is sh-like in this context.

  • ssh-agent tries to tell if your shell is sh-like or csh-like, and generates shell code accordingly. In other words it behaves like ssh-agent -s or ssh-agent -c, depending on what it "thinks" about your shell. If you know your shell is zsh then you may prefer eval "$(ssh-agent -s)" in case the tool guesses wrong for some reason. Usually this is not needed though.

  • Almost always you should avoid eval, in general it's hard to use it safely, some say "eval is evil". With ssh-agent it's OK though, because ssh-agent is deliberately designed to be used with eval, it generates fully controlled shell code that stays away from areas and pitfalls that make eval "evil".

Kamil Maciorowski
  • 69,815
  • 22
  • 136
  • 202