How to autostart a program after network connection on Ubuntu?

I don't know an elegant way, but here's an approach that should work.

Write a script that tests to see if you're online. If not, sleep for awhile and then loop back to test again. When you come online, start chrome and exit, etc.. Put that script in your autostart directory.

In bash, the wait command is sleep. It takes an argument of the number of seconds you want to wait. It keeps your script from testing too often and using up resources.

The trick is to figure out if you're online. One way to do that is to do something small that will fail if you're not online. Below is a hack that should be enough to get you started (if you know bash). I found the wget command trick on the web somewhere and I'm not sure exactly what it does, but it's quick and it works.

You'll have to substitute your path for chrome.

The ampersand at the end of the chrome line causes chrome to execute in the background so your script won't hang on that line until chrome exits. It will continue and terminate normally, leaving chrome running on its own.

If you want to get fancy, there's a way to save the process id of the task to a file, etc., so you can easily find it and kill it later if you decide you don't want chrome to start when you come online in a particular session. But, that's a bit beyond the scope of your question. (and I don't remember how to do it ;) )

#!/bin/bash

function online {
  ## Test if online - prototype code
  wget -q -O /dev/null --timeout=5 http://udc.msn.com/c.gif
  return $?
}

until online
do
  sleep 5
done

/opt/google/chrome/google-chrome &

Tags:

Lubuntu