How do I get my script to run BEFORE any shutdown sequence like unmounting my external drive

I have a back up script in ~/scripts/backup.sh and my upstart conf in ~/.config/upstart/shutdown.conf.

description "my shutdown script"
start on desktop-end

task
console log
script
  exec ~/scripts/backup.sh start
end script

My script backs up to an external hard drive on desktop-end but the external hard drive gets unmounted before my script is called.

How can I precede the shutdown sequence with my script and then resume only when my script is done?

I tried the solution from this post but the hook on starting rc isn't working.

Thanks.


Solution 1:

Credit to this posted answer

First, I don't know why upstart works at all since Ubuntu 15.10 should be using systemd instead. So I used systemd to solve my problem.

I create a systemd "unit" called backup.service

[Unit]
Description=Backup script
DefaultDependencies=no
RequiresMountsFor=/mnt/D21EF5DA1EF5B795 /home /media/external
Before=shutdown.target reboot.target halt.target


[Service]
ExecStart=/bin/bash /home/deanresin/scripts/backup.sh start
Type=oneshot

[Install]
WantedBy=multi-user.target

RequiresMountsFor ensures those hard drives remain mounted before and during the script. Before=shutdown.target reboot.target halt.target is the hook that will call the backup script.

Put the backup.service file in /etc/systemd/system and sudo chmod u+x /etc/systemd/system/backup.service to make it executable.

Now enable the backup.service by systemctl enable backup.service

And voila! The backup script "backup.sh" should be called at restart,shutdown or halt and executed before the specified drives are unmounted.