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,705

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
  • 309,379