When working with git and a server via SSH, there’s a common headache: ssh-agent
(or other processes) keep running in the background, even after you exit the console with exit
. This leads to dozens of ssh-agent
processes piling up… and most hosting providers have strict limits on the number of active processes. Not to mention, they just waste resources for no reason. And we’re all for efficiency, right?
So, here’s a quick recipe on how to automatically terminate ssh-agent
on exit to avoid errors like:
error: cannot create thread: Resource temporarily unavailable
fatal: send-pack: unable to fork off sideband demultiplexer
-bash: fork: retry: Resource temporarily unavailable
-bash: fork: Resource temporarily unavailable
Alrighty… Normally, ssh-agent
is launched with:
eval `ssh-agent -s` && ssh-add ./.ssh/
Of course, the right way to close it is manually (ssh-agent -k
), but let’s be real – who remembers to do that?
The Fix:
I connect using this one-liner:
cd <your_domain_name>.com/public_html && eval `ssh-agent -s` && ssh-add ./.ssh/id_rsa && trap "ssh-agent -k" EXIT
What does this command do?
- Moves to the website directory (
cd <yourdomain>.ru/public_html
). - Starts
ssh-agent
(eval `ssh-agent -s`
). - Adds the SSH key (
ssh-add ./.ssh/
). - Sets up a
trap
that automatically terminatesssh-agent
when exiting. - If you type
exit
,ssh-agent
shuts down like a good boy!
For even more reliability, you can use:
cd <your_domain_name>.com/public_html && eval `ssh-agent -s` && ssh-add ./.ssh/id_rsa && trap "ssh-agent -k" HUP
EXIT
terminates ssh-agent
when you manually exit the shell with exit
, whereas HUP
also kills ssh-agent
if the SSH connection is lost. So, if you forget to type exit
and just close the window – everything cleans itself up automatically.
How to check if ssh-agent
is still running?
ps aux | grep ssh-agent
If there’s no ssh-agent
in the output, life is good.
If it’s still hanging around, forcefully terminate all greedy lingering ssh-agent
processes:
pkill -9 ssh-agent
(Note that pkill -9
will kill all ssh-agent
processes indiscriminately. If multiple users are on the server, this might terminate their ssh-agent
too. To kill only your own:
pkill -u $USER ssh-agent
)
Good lucks!