I'm trying to create a script that runs a few commands that take a long time to execute and require a constant connection, but

autossh user@server
wait $! #or wait ${!}


doesn't work (I'm assuming because autossh drops into the background). The GUI pops up asking for a password and while that is up the next few commands are run.

How do I wait for an established connection before running the next commands?


autossh -f => "...causes autossh to drop to the background before running ssh..."

so with the -f wait does nothing, without it, you wait on the ssh which will never end...

  • Do you need to be connected, or are you able to use something like "screen" to just run it and re-connect later? I think you need to change !$ into ${!} as shown here – CaptSpify Dec 20 '11 at 20:12
  • yes, it has to have a "constant" connection - like a backup, essentially the connection is just poor, and autossh facilitates the reconnect automatically – jtzero Dec 20 '11 at 20:30
  • 2
    Are you doing any port forwarding? You could have a try step in your script that netcats to the autossh echo port to see if it's open before proceeding. netcat has a zero I/O option -z that will just check to see if the TCP port is open. – Jodie C Mar 12 '12 at 3:03
  • this is a simple solution and it worked, post it in a n answer – jtzero May 22 '12 at 15:24

If I understand you correctly your problem is that you want to wait until authentication succeeds before continuing with the rest of your script.

I would solve this with public key authentication and ssh-agent.

Once this is configured and ssh-agent is running, ssh won't ask for a password and your script will authenticate correctly each time. (It's not quite the same as ensuring the connection is working but it may suffice for your purposes)

Two other workarounds come to mind:

  1. Use tcptraceroute in a while loop to check that a port forward is working (assuming you have port forwards in use or can create one for this purpose). Don't break out of the loop until you get a successful reply.
  2. Place your long-running commands in a script on the remote side, and execute those in screen or nohup. One trick I've used in the past is to generate a script, then copy it to the remote side, then execute it using nohup.
| improve this answer | |

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.