Fish function for ssh-agent
ssh-agent
When you run ssh-agent, it prints out something like the following
bash > ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-XXXXXXQLU0Co/agent.19874; export SSH_AUTH_SOCK;
SSH_AGENT_PID=19875; export SSH_AGENT_PID;
echo Agent pid 19875;
In bash, you can use eval and a subshell to load the variables into the current shell's environment
bash > eval $(ssh-agent)
Agent pid 20037
bash > env | grep SSH
SSH_AUTH_SOCK=/tmp/ssh-XXXXXXPeMMg6/agent.20036
SSH_AGENT_PID=20037
However, if you try to do the same in fish, you will encounter the following error. (Note that fish doesn't use $ in subshell invocation.)
fish > eval (ssh-agent)
fish: Unsupported use of '='. In fish, please use 'set SSH_AUTH_SOCK /tmp/ssh-XXXXXX1pfQkd/agent.20237'.
ENV_VAR=value
type declarations are not valid in fish, you have to use the set
builtin. Likewise, you don't use export, add the -gx flag to set to add a variable to the environment.
Fish function definition
Fish can auto-load functions if they are placed in .config/fish/functions and they can shadow existing command names.
function ssh-agent
set output (command ssh-agent)
set -gx SSH_AUTH_SOCK (string split --no-empty ';' $output | awk -F= '/SSH_AUTH_SOCK=/{print $2}')
set -gx SSH_AGENT_PID (string split --no-empty ';' $output | awk -F= '/SSH_AGENT_PID=/{print $2}')
end
Line 2, we invoke a subshell and save the output from ssh-agent
to the output
variable. The subshell is command ssh-agent
so we call the real ssh-agent as the fish function
has the same name.
We use the fish builtin string to split the ssh-agent output into lines which we then filter and extract with awk
fish > string split --no-empty ';' $output
SSH_AUTH_SOCK=/tmp/ssh-XXXXXX3mdwgI/agent.20479
export SSH_AUTH_SOCK
SSH_AGENT_PID=20480
export SSH_AGENT_PID
echo Agent pid 20480
You could probably do without the string builtin and just use awk but this was easier
To use, you don't even need to run it like eval (ssh-agent), you can just run the bare ssh-agent and the function correctly exports the vars
fish > ssh-agent
fish > env | grep SSH
SSH_AGENT_PID=20875
SSH_AUTH_SOCK=/tmp/ssh-XXXXXXSJwBjy/agent.20874
fish > ssh-add ~/.ssh/id_ed25519
Identity added: ~/.ssh/id_ed25519