2

In order to sync my home and work file systems I need to go via an intermediary computer and use port forwarding. Let us call the home computer A, the intermediate one B and the work computer C. From the command line I do this

ssh -N -f -L 2025:C:22 me_B@B && unison foo ssh://me_C@localhost:2025/foo
  • I would like to put this one-liner into a bash script. How can I make it quit gracefully at the end and not leave any port forwarding still set up?
Simd
  • 19,447
  • 42
  • 136
  • 271
  • Why the down vote? It is a programming question. – Simd Oct 22 '14 at 10:25
  • It should just work automatically, if you put that into a script. – John Zwinck Oct 22 '14 at 12:06
  • @JohnZwinck It leaves behind "ssh -N -f -L 2025:C:22 me_B@B" which I can see by doing `ps auwx|grep ssh`. – Simd Oct 22 '14 at 12:08
  • Hmm, that surprises me. You can try using `trap EXIT` in Bash to run a function when the master script exits, and in that function you can kill the PID of `ssh` (which you can get by `$!` if you start it in the background initially). – John Zwinck Oct 22 '14 at 12:11
  • @JohnZwinck This sounds good but I may need more hand holding than that I am afraid. If you get a chance to add an answer that would be great. – Simd Oct 22 '14 at 12:13

1 Answers1

1
ssh -N -f -L 2025:C:22 me_B@B &
pid=$! # ssh PID
rc=$? # ssh return code

# set up to kill ssh when this script finishes
function finish {
  kill $pid
}
trap finish EXIT

[ $rc -eq 0 ] && unison foo ssh://me_C@localhost:2025/foo
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Thanks. This almost works perfectly (I have to remove the & so I can enter the ssh passwords). I think as a result of this I get "Looking for changes Waiting for changes from server Reconciling changes Nothing to do: replicas have not changed since last sync. kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec] " Not putting it in the background mucks things up it seems but I have to do be able to enter the passwords. – Simd Oct 22 '14 at 12:49
  • If `kill` is printing its usage, then `$pid` is not right somehow. Maybe try `export pid=$!` after launching ssh? I'm not too sure right now. – John Zwinck Oct 22 '14 at 14:17