A script was automatically creating an SSH tunnel in the background with a simple command like this, which works:
ssh -R 19000:localhost:22 [email protected] -i ~/.ssh/keyfile &
This answer describes how to set up dynamically assigned ports and redirect the output of SSH such that the port can be captured by my script. It works too:
ssh -R 0:localhost:2222 [email protected] -i ~/.ssh/keyfile 3>&1 1>&2 2>&3 | sed -n "s/^Allocated port \([0-9]*\) for/port \0/p" > portfile.txt &
Separately, this article suggests a method to have tunnels auto-closing after a specific time, which also works on its own:
ssh -R 19000:localhost:22 [email protected] -i ~/.ssh/keyfile sleep 10;
Now I wish to combine them into one line but the tunnel collapses before my sleep command can execute:
(ssh -R 0:localhost:22 [email protected] -i ~/.ssh/keyfile 3>&1 1>&2 2>&3 "sleep 1" | sed -n "s/^Allocated port \([0-9]*\) for remote forward to localhost:2222/\1/p" > portfile.txt); sleep 10 &
Output is redirected and the port number is written to the file as expected, but immediately the tunnel closes and the sleep command runs.
Please can someone explain what I'm doing / doing wrong in this command, and why it doesn't work?
Try to send your initial SSH tunnel to background. Add thees options '-fN'