I'd like to run a .sh file using bash on logout and shutdown of Ubuntu. I have searched up and down the web and have found only fixes for KDE and GNOME. The script is simple, I just need to know if I can add the line of code to the "logoff/shutdown" file or if I need to reference it in another script.

  • 1
    Put symlinks to executables in /etc/init.d in /etc/rc0.d, and /etc/rc6.d – Yet Another User May 10 '13 at 1:21
  • 1
    Please consider accepting the updated answer (using systemd) so people would see it on top. – Jonathan Y. Nov 25 '17 at 22:24

To execute a script upon logout:

Add the following line:

session-cleanup-script=/path/to/script

in /etc/lightdm/lightdm.conf file.

You have to restart lightdm in order that this change to take effect. To do this go in tty1 using Ctrl+Alt+F1, login with your username and password and run the following command:

sudo service lightdm restart

Note: use Ctrl+Alt+F7 to switch to the graphical session

To execute a script upon reboot:

  1. Put your script in /etc/rc0.d
  2. Make it executable: sudo chmod +x K99_script
  3. Notes:
    • The scripts in this directory are executed in alphabetical order.
    • The name of your script must begin with K99 to run at the right time.

To execute a script at shutdown:

  1. Put your script in /etc/rc6.d
  2. Make it executable: sudo chmod +x K99_script
  3. Notes:
    • The scripts in this directory are executed in alphabetical order.
    • The name of your script must begin with K99 to run at the right time.

Sources:

  • 4
    It's conventional to name scripts starting with K for 'Kill' and S for 'Start'. – kiri Oct 27 '13 at 13:00
  • What if the script needs sudo privileges? As far as I can tell, the /etc/rc6.d scripts are run as user, and cannot use gksudo. – Urhixidur Aug 13 '14 at 17:10
  • 1
    doesn't work for me with 14.04, is there any change or unspecified important fact? – tomasb Oct 1 '14 at 0:35
  • 2
    K99 advice is not good for shutdown/reboot if you want to save some data because it happens AFTER unmount AND K is used to disable script (see /etc/rcS.d/README), use S for start and place it before unmounts, for bootup place your script after mount, got stuck on this because this misinformation, resolved with S as the first letter – tomasb Nov 18 '14 at 18:18
  • 6
    This is very wrong: i) script names need to start with a K for runlevels 0, 1 and 6 and S for runlevels 2, 3, 4 and 5; ii) you don't need to call the script K99_foo, the number just determines the order the scripts are run in. You need to chose one that is larger than the others if you want it to be run last; iii) Runlevel 0 is not for reboot!; It's for shutdown. 6 is for reboot. iv) scripts have no business being in the /etc/rcN.d directories. They should instead be in /etc/init.d and linked to /etc/rcN.d. – terdon Jul 24 '15 at 11:11

How to do it with systemd

If you find this thread after June 2016, Ubuntu and its derivatives including Mint will be using systemd to control system initialization and shutdown. I had problems with the old approach so researched the systemd way.

With systemd you create one or two files to call your scripts using the templates below, and execute a command. Simple.


GUI Version

First create the scripts you want to run at startup and/or shutdown. I created .scopening_atstart and .scfullcopy_atend.

Then make sure that they are both executable by right clicking the file, selecting properties and making sure that, under permissions, you have ticked Allow executing file as a program.

The two files I created populate and save the contents of a ramdisk. They also create a file in my home directory to prove that the service is working. They were of the form:

#!/bin/sh
cp -pru /home/john/zRamdisk/subdirectory1/* /home/john/.wine/drive_c/subdirectory1/
rm /home/john/stop_time
date +%D' '%T > /home/john/stop_time

Then I opened my file manager as root, opened /etc/systemd/system and created a file startup.service and a file save-ramdisk.service. Obviously you can choose your own names and generic names could have included a startup file called johns_start.service and a shutdown file called johns_shutdown.service. Just don't pick existing service names.

[Unit]
Description=Startup Applications

[Service]
Type=oneshot
RemainAfterExit=false
ExecStart=/home/john/.scopening_atstart

[Install]
WantedBy=multi-user.target

and

[Unit]
Description=Save Ramdisk to Wine drive C

[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/true
ExecStop=/home/john/.scfullcopy_atend

[Install]
WantedBy=multi-user.target

You can use the same service files, substituting the full path of your executable script for mine.

Finally for each one execute the command systemctl enable your_files_name (but without the suffix service). So my first one was systemctl enable startup

Reboot the computer once to start the services. The start service will be executed whenever systemd enters the multi-user target and the stop service when it exits the multi-user target. Alternative service files with different activation conditions will be described below.


CLI (Command Line) Version

This description assumes that you operate from your home directory rather than /home/john, use sudo as needed, and your choice of editor where I write vim or svim.

Create startup and shutdown shell scripts with the first line #!/bin/sh and make them executable using chmod +x my_new_filename.

Create two files as above, or in this example, one file to handle startup and shutdown tasks. I will execute scripts in my home directory but @don_crissti showed some alternatives at Stack Exchange.

svim /etc/systemd/system/start_and_stop.service

and copy in the file content:

[Unit]
Description=Run Scripts at Start and Stop

[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/home/john/.startup_commands  #your paths and filenames
ExecStop=/home/john/.shutdown_commands

[Install]
WantedBy=multi-user.target

Then Enable the Service with the command:

systemctl enable start_and_stop

and reboot your system after which the services will be active. The commands systemctl is-enabled start_and_stop and systemctl is-active start_and_stop can be used in monitoring your new services.


Changing the Trigger Conditions for Shutdown

The files above all use the open or close of the multi-user environment to initiate running the scripts. The file below uses the beginning of four potential shutdown processes to initiate its scripts. Adding or removing the targets on the Before line + the WantedBy line will let you make finer distinctions:

This file was proposed in an answer at Unix & Linux by @Matthias but I was unable to get it to run until I added an Install section.

Again, edit the script in /etc/systemd/service/ and enable it using systemctl enable your_file_name. When I changed the targets I used the systemclt disable file_name command and then re-enabled it which symlinked it to the target directories. Reboot and the service will be operating.

[Unit]
Description=Do something required
DefaultDependencies=no
Before=shutdown.target reboot.target halt.target
# This works because it is installed in the target and will be
#   executed before the target state is entered
# Also consider kexec.target

[Service]
Type=oneshot
ExecStart=/home/john/.my_script  #your path and filename

[Install]
WantedBy=halt.target reboot.target shutdown.target
  • 1
    Although your post is correct, I'd suggest improving it by adding example of how such steps can be done with systems. Please let me know once you edit you post. Thanks and welcome to AskUbuntu – Sergiy Kolodyazhnyy Jul 8 '16 at 0:01
  • Hi Serg, do you mean examples such as in the linked post or did you have something else in mind? Second, I'm not sure how to "let you know" as I can't find a mechanism for contacting another SO user. – John 9631 Jul 10 '16 at 2:43
  • Yes, you could provide an example same as in your other post. Just saying " go to that other link" is not very good and makes your answer look lazy. Also for contacting another SO user use @ before user name, for example @Serg – Sergiy Kolodyazhnyy Jul 10 '16 at 2:50
  • Much improved. Very well, keep up the good job ! – Sergiy Kolodyazhnyy Jul 10 '16 at 4:05
  • 1
    according to man systemd.unit user created files can be placed in $XDG_CONFIG_HOME/systemd/user and other local user locations – Antonios Hadjigeorgalis Dec 16 '16 at 17:43

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.