How to Run a Script on Unity Login/Logout

scriptsunityupstart

I have two scripts – one to mount some folders over SSHFS – and one to unmount.

I would like to launch the mount script when my default Ubuntu desktop is launched (after I log in at the graphical console) – and the unmount script when I "Log Out…" from the cog-wheel at the top-right of the desktop.

Please can someone tell me how to achieve this? What are the most convenient/standard hooks to run commands on desktop launch / exit?

Best Answer

Considering your requirement of running a job when you login to Unity and not for other logins, an Upstart session job seems perfect.

You may have noticed it: processes that you run after a GUI login are under a second init process. This init is a proper Upstart init, and you can start and stop session jobs based on events emitted by it. No root privileges needed at all. Better yet (or worse depending on the perspective), this is not yet completely supported for headless systems. An SSH login didn't start the user init from a quick test that I made just now.

To create a session job, make a new .conf file in ~/.config/upstart. That's the default primary directory for Upstart session jobs ($XDG_CONFIG_HOME/upstart), create it if doesn't exist. Here's an example job:

tee ~/.config/upstart/myjob.conf <<EOF
description "My job"
start on desktop-start
stop on desktop-end

script 
       firefox 'http://upstart.ubuntu.com/cookbook/#session-job'
end script
EOF

You can manually control it:

start myjob 
# or
initctl start myjob

The service command are used to control system jobs (those in /etc/init.d or /etc/init). For controlling session jobs, one needs to use the initctl command, which is used to interact with Upstart.

See man upstart-events for more events you can use.

Related Question