使用 systemd 服务创建文件

使用 systemd 服务创建文件

我正在尝试创建一个 systemd 服务来自动清除目录中的旧文件。如果我要手动执行此操作,我将使用如下命令

$ /usr/bin/touch -t $(/usr/bin/date -d'-7day' +%Y%m%d%H%M) /tmp/cutoff
$ /usr/bin/find /path/to/dir ! -newer /tmp/cutoff -exec rm {} \;

前一行确实会在/tmp目录中生成占位文件。但是,以下服务定义

[Unit]
Description=Cleanup index cache left behind by bup backup
Type=oneshot

[Service]
ExecStart=/usr/bin/touch -t $(/usr/bin/date -d'-7day' +%%Y%%m%%d%%H%%M) /tmp/cutoff
SyslogIdentifier=%p

无法生成占位符

$ /usr/bin/touch -t $(/usr/bin/date -d'-7day' +%Y%m%d%H%M) /tmp/cutoff
$ ls -l /tmp/cutoff
-rw-r--r--. 1 user group 0 Mar 20 14:36 /tmp/cutoff
$ rm /tmp/cutoff
$ sudo systemctl start cleanup_index_cache
$ ls -l /tmp/cutoff
ls: cannot access '/tmp/cutoff': No such file or directory
$ 
$ sudo systemctl start cleanup.service
$ ls -l /tmp/cutoff

是否有办法使用 systemd 删除超过一定时间的文件/目录?将 shell 命令转录为 systemd 指令是否缺少了什么?

答案1

systemd 不会ExecStart=通过 shell 发送命令及其相关命令。它会直接执行这些命令。因此您不能使用诸如这样的 shell 结构$()

目前还不清楚你为什么要生成一个日期并用它来处理文件。find完全有能力自己找到超过一定时间的文件。

从手册页中:

       -mtime n
              File's  data was last modified n*24 hours ago.  See the comments
              for -atime to understand how rounding affects the interpretation
              of file modification times.

那段解释道:

       -atime n
              File  was  last  accessed n*24 hours ago.  When find figures out
              how many 24-hour periods ago the file  was  last  accessed,  any
              fractional part is ignored, so to match -atime +1, a file has to
              have been accessed at least two days ago.

find还能够自行删除文件,而不需要调用rm(出于各种原因,这样做可能不是一个好主意)。

       -delete
              Delete files; true if removal succeeded.  If the removal failed,
              an  error message is issued.  If -delete fails, find's exit sta‐
              tus will be nonzero (when it eventually exits).  Use of  -delete
              automatically turns on the `-depth' option.

              Warnings:  Don't  forget that the find command line is evaluated
              as an expression, so putting -delete first will make find try to
              delete everything below the starting points you specified.  When
              testing a find command line that you later intend  to  use  with
              -delete,  you should explicitly specify -depth in order to avoid
              later surprises.  Because -delete  implies  -depth,  you  cannot
              usefully use -prune and -delete together.

因此,要删除超过 7 天的文件,您可以直接运行find,无需执行其他任何有趣的操作:

/usr/bin/find /directory -mtime +6 -delete

答案2

systemd-tmpfiles是 systemd 的一项功能,可以配置为自动从目录中清除旧文件。无需每次需要清理目录时都启动新服务,只需创建一个包含/etc/tmpfiles.d/以下内容的文件:

# /etc/tmpfiles.d/cleanup_index_cache.conf
d /path/to/dir - - - 7d

参考:tmp文件.d (5)systemd-tmp文件 (8)

相关内容