Kill an SSH tunnel after X minutes even if it's still being used?
Here's a cleaner way of doing it that has been proposed before:
ssh -f -N -L 14880:internalserver:3306 gateway.example.com &
PIDSSH=$!
( sleep 600 ; echo "Timeout." ; kill $PIDSSH ) &
PIDSLEEP=$!
wait $PIDSSH
kill $PIDSLEEP && echo "Session ended before timeout"
wait
However you don't get an error code from ssh, but that could be arranged.
The expect package has the timeout command as one of its examples. You could wrap your whole script with a call to that.
Or something like:
ssh -f -N -L 14880:internalserver:3306 gateway.example.com &
PID=$!
nohup "sleep 600; kill $PID" &