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

2
  • 4
    your script is missing a then Feb 4, 2020 at 7:42
  • 1
    I think it would be much more reliable to delete the file on startup - this would work in case of a power loss or a hard reboot.
    – Sergey
    Feb 4, 2020 at 22:15

1 Answer 1

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?

4
  • 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 4, 2020 at 8: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 4, 2020 at 17:11
  • 1
    I copied that from the official manual ;) Here: tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-6.html It is a method of formatting not actual code
    – Rinzwind
    Feb 4, 2020 at 17:29
  • @Rinzwind Actual official manual: if
    – wjandrea
    Feb 4, 2020 at 23:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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