So I wanted to call two background ssh processes:

ssh -D localhost:8087 -fN aws-gateway-vpc1
ssh -D localhost:8088 -fN aws-gateway-vpc2

These gateways don't have the benefit of letting me set an authorized_keys file, so I must be prompted for my interactive password. That is why I'm using the -f flag and not the shell's & which will only background the process after I authenticate interactively.

In this scenario I appear to be unable to use the $! bash variable to get the pid of the recently [self] backgrounded process.

What other options do I have to find the correct pid to kill later if interrupted?


The $! doesn't work, as you say, because it hasn't been backgrounded by the current shell. In fact, the ssh process isn't even a child of the shell you launched it from. On my Arch system, at least, it is run as a child of PID 1, the init process.

So, to get the PID, you can simply use ps:

$ ssh -f  localhost sleep 100
$ ps aux | grep '[s]sh.*-f'
terdon   20648  0.0  0.0  43308   680 ?        Ss   12:15   0:00 ssh -f localhost sleep 100

That tells me the PID is 20648*.

Alternatively, and more simply, use pgrep -f:

$ pgrep -f 'ssh.*-f'

And, to kill it (them):

pkill -f 'ssh.*-f'

* See this question if you're wondering about the [s] in the grep command.

  • 1
    Thanks; for my purposes I used for P in ``ps -ax |grep 'ssh -D localhost:808[89] -fN'|cut -d ' ' -f 1``; do kill $P; done but not with double back-ticks, that's a md commenting thing going on here. – dlamblin Aug 29 '17 at 10:10
  • @dlamblin if that's all you want, use pkill -f 'ssh -D localhost:808[89]' (see updated answer). – terdon Aug 29 '17 at 10:13

Finding the pid by grepping might be error prone. Alternative option would be to use ControlPath and ControlMaster options of SSH. This way you will be able to have your ssh command listen on a control socket and wait for commands from subsequent ssh calls.

Try this

ssh -D localhost:8087 -S /tmp/.ssh-aws-gateway-vpc1 -M -fN aws-gateway-vpc1
# (...)
# later, when you want to terminate ssh connection
ssh -S /tmp/.ssh-aws-gateway-vpc1 -O exit aws-gateway-vpc1

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.