How to automatically run a script when logging into Ubuntu Desktop

There are circumstances where you wish to have a script run automatically when you log in to Ubuntu Desktop. Such a script can configure various user-specific or system-wide settings on your Ubuntu system, upon user's desktop login.

In Linux, there are start-up scripts named ~/.bash_profile, ~/.bashrc, or ~/.profile which get executed when you start a shell. However, in Ubuntu Desktop, such start-up scripts get executed when you open up a terminal window, but NOT when you log in to Ubuntu Desktop GUI. Also, when you open multiple terminal windows, these kinds of start-up scripts are executed as many times, in order to initialize user's shell environment in terminal windows.

If what you want is to run a script at the time of user's Ubuntu Desktop login, you can follow this guideline.

Create a XDG configuration file for the start-up script you want to run.

$ vi ~/.config/autostart/my_script.desktop
[Desktop Entry]
Type=Application
Name=My Script
Exec=~/bin/my_custom_script.sh
Icon=system-run
X-GNOME-Autostart-enabled=true

The above XDG configuration file will set up "user-specific" auto-start. If you want all users to use the same start-up script "system-wide", create a similar XDG configuration file in the following location instead.

$ sudo vi /etc/xdg/autostart/my_script.desktop
[Desktop Entry]
Type=Application
Name=My Script
Exec=sudo /sbin/my_custom_script.sh
Icon=system-run
X-GNOME-Autostart-enabled=true

If the start-up script requires sudo access like an above example, you will need to set up password-less sudo.

Subscribe to Xmodulo

Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.

The following two tabs change content below.
Dan Nanni is the founder and also a regular contributor of Xmodulo.com. He is a Linux/FOSS enthusiast who loves to get his hands dirty with his Linux box. He likes to procrastinate when he is supposed to be busy and productive. When he is otherwise free, he likes to watch movies and shop for the coolest gadgets.

One thought on “How to automatically run a script when logging into Ubuntu Desktop

  1. this was very usefull, but I have 3 more questions.

    1) how to do similar task, when you log out.
    2) how to do similar task, when locking pc
    3) how to do similar task, when unlocking pc

    hope you can help

Leave a comment

Your email address will not be published. Required fields are marked *

Current ye@r *