I have a problem whereby my script keeps spawning new ssh processes. This shouldn't happen I know, but I would like to clean the old ones up from time to time.

If I do :

ps -ef | grep "ssh" | awk '{print $2}'

I get a list of all the PIDs of the ssh processes running.

I would like to kill all of them, apart from the last one or two that has been spawned (The processes with the highest PID numbers).

How would I go about this?

  • If my answer solved your problem, please accept it by clicking the checkmark next to it. Thank you! – Jeff Schaller Feb 24 at 14:23
while [ $(pgrep -c ssh) -gt 1 ]
  pkill --oldest -f ssh

As long as there's more than one ssh process, kill the oldest ("least recently started") one(s). Least-recently-started might be a better metric than "lowest PID" in case your PID space wrapped around or you used randomized PIDs.

  • You could be more specific with the pgrep and pkills, if needed -- to match a longer process name & arg string, or to match only your user (-u engineer999), etc. – Jeff Schaller Feb 19 at 16:41
  • Thanks Jeff. A bit off-topic, but is it dangerous to have all of these ssh processes spawning all the time? I'm using just a Rasberry Pi. I guess only the latest process will be active, but then, there is probably a limit to the number of processes I can have – Engineer999 Feb 19 at 16:51
  • Hard to say without knowing what the processes are doing. Computers compute, so if the process is doing something you expect, that's one thing. If it's getting in your way, it might be worth a new question, detailing out what it's doing and what's going wrong with it. – Jeff Schaller Feb 19 at 18:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.