18.04.4 关机时删除文件

Séb*_*rre 5 reboot bash shutdown rsync

如果我重新启动或关闭我的 Ubuntu 18.04.4,我想删除一个锁定文件。

我创建了“usr/local/sbin/delete_lock.sh”

#!/bin/bash
lock="/home/sebastien/rsync.lock"
if [ -f "$lock" ];
rm $lock;
fi
Run Code Online (Sandbox Code Playgroud)

然后是另一个“/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
Run Code Online (Sandbox Code Playgroud)

然后我启动

sudo systemctl enable run_on_shutdown.service
Run Code Online (Sandbox Code Playgroud)

并重新启动

知道为什么不删除 rsync.lock 文件吗?非常感谢

Rin*_*ind 11

所述if在bash结构是:

if [expression];    
then    
code if 'expression' is true.    
fi 
Run Code Online (Sandbox Code Playgroud)

所以你确实缺少一个then.

#!/bin/bash
lock="/home/sebastien/rsync.lock"
if [ -f "$lock" ];
then
rm $lock;
fi
Run Code Online (Sandbox Code Playgroud)

我可以提出一些建议吗:

你让这太复杂了。

将锁定文件放入/tmp/. 该目录在每次重新启动时都会被清除,它是放置锁定文件的理想目录,而无需您进行任何额外操作。参见例如/tmp 目录是如何清理的?

此方法还支持从/etc/tmpfiles.d. 请参阅如何清理 /tmp 目录?

  • 另一种方法是使用cronjob,只需使用@reboot,但该文件将在启动时被删除。如果这对您来说方便,您可以尝试一下。 (2认同)
  • 它实际上是`if command;` 不是`if [expression];`。`[` 只是一个命令。事实上,如果没有 `[]` 中的空格,它就无法工作,因为没有 `[-f` 命令。 (2认同)