5

I'd like to delete a lock file if I reboot or shutdown my Ubuntu 18.04.4.

I created "usr/local/sbin/delete_lock.sh" with

#!/bin/bash
lock="/home/sebastien/rsync.lock"
if [ -f "$lock" ];
rm $lock;
fi

and then another "/etc/systemd/system/run_on_shutdown.service":

[Unit]
Description=Delete lock file at shutdown - /etc/systemd/system/run_on_shutdown.service
DefaultDependencies=no
Before=shutdown.target halt.target
# If your script requires any mounted directories, add them below: 
RequiresMountsFor=/home

[Service]
Type=oneshot
ExecStart=/usr/local/sbin/delete_lock.sh

[Install]
WantedBy=halt.target shutdown.target

then I launch

sudo systemctl enable run_on_shutdown.service

And restart

Any idea why the rsync.lock file isn't deleted ? Many thanks

K7AAY
  • 17,202

1 Answers1

11

The base for the if constructions in bash is:

if [expression];    
then    
code if 'expression' is true.    
fi 

so you are indeed missing a then.

#!/bin/bash
lock="/home/sebastien/rsync.lock"
if [ -f "$lock" ];
then
rm $lock;
fi

Might I suggest something:

You are making this far too complicated.

Put the lock file in /tmp/. That directory is cleaned out on every reboot and is the ideal directory to put lock files without the need for you to anything extra. See for instance How is the /tmp directory cleaned up?

This method also supports an extension from the content of /etc/tmpfiles.d. See How is the /tmp directory cleaned up?

Rinzwind
  • 299,756
  • 2
    Another way would be to use a cronjob, simply use @reboot, but the file would be deleted at startup then. If this is convenient to you, you could give that a try. – s1mmel Feb 04 '20 at 08:07
  • 2
    It's actually if command; not if [expression];. [ is just a command. In fact it won't work without the spaces inside the [] because there's no [-f command. – user253751 Feb 04 '20 at 17:11
  • 1
    I copied that from the official manual ;) Here: http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-6.html It is a method of formatting not actual code – Rinzwind Feb 04 '20 at 17:29
  • @Rinzwind Actual official manual: if – wjandrea Feb 04 '20 at 23:03