I have a sample sh
script on my Linux environment, which basically run's the ssh-agent
for the current shell, adds a key to it and runs two git commands:
#!/bin/bash
eval "$(ssh-agent -s)"
ssh-add /home/duvdevan/.ssh/id_rsa
git -C /var/www/duvdevan/ reset --hard origin/master
git -C /var/www/duvdevan/ pull origin master
Script actually works fine, but every time I run it I get a new process so I think it might become a performance issue and I might end up having useless processes out there.
An example of the output:
Agent pid 12109
Identity added: /home/duvdevan/.ssh/custom_rsa (rsa w/o comment)
Also, along with all this, is it possible to find an existing ssh-agent
process and add my keys into it?
The accepted answer did not work for me under Ubuntu 14.04.
The test to check if the ssh-agent is running I have to use is:
And I am starting the ssh-agent with:
Otherwise the
SSH_AGENT_PID
is not set.The following seems to work under both Ubuntu 14.04 and 18.04.
Using
$SSH_AGENT_PID
can only test thessh-agent
but miss identities when it is not yet addedSo it would be save to check it with
ssh-add -l
with an expect script like example below:So when both
ssh-agent
andssh-add -l
are put to run on a bash script:then it would always check and assuring that the connection is running:
You can also emulate the repeating of commands on above script with do while
No, really, how to check if ssh-agent is already running in bash?
Answers so far don't appear to answer the original question...
Here's what works for me:
This was taken from: https://stackoverflow.com/a/15774758
You can modify line #1 to:
And then at the end of the script you can do:
If you want it to be killed right after the script exits, you can just add this after the eval line:
Or:
$SSH_AGENT_PID
gets set in the eval ofssh-agent -s
.You should be able to find running ssh-agents by scanning through
/tmp/ssh-*
and reconstruct theSSH_AGENT
variables from it (SSH_AUTH_SOCK
andSSH_AGENT_PID
).ps -p $SSH_AGENT_PID > /dev/null || eval "$(ssh-agent -s)"
Single line command. Run for the first time will start ssh-agent. Run for the second time will not start the ssh-agent. Simple and Elegant Mate !!!