Home > System Tutorial > LINUX > body text

Linux schedules automatic deletion of files in a directory at regular intervals

WBOY
Release: 2024-07-23 09:50:25
Original
841 people have browsed it

Linux schedules automatic deletion of files in a directory at regular intervals

To achieve scheduled deletion of all files in a certain directory, you need to use the Linux crontab command, which can be achieved with a shell script. For example, to delete all cache files under /tmp, do the following:

[root@localhost ~]# vi /etc/init.d/delete.sh

按i并复制下面内容到delete.sh文件内,之后按shift+: 输入wq保存并退出。

#!/bin/bash
dir=/tmp //需要清空的目录名称
files=`ls ${dir}`
for file in $files
do
if [ -e ${dir}/${file} ];then
rm -f ${dir}/${file}
fi
done
Copy after login

Then give this script 755 permissions, the code is as follows:

[root@localhost ~]# chmod 755 /etc/init.d/delete.sh
Copy after login

Next, use the crontab command to set the time. For example, clear all files in the /tmp directory at 3 a.m. every day. Running the following command will enter the vim editing interface.

[root@localhost ~]# crontab –e

粘贴以下代码;

0 3 * * * /etc/init.d/delete.sh

保存并退出,现在定时工作已经完成了,每天凌晨3点自动清空/tmp目录下的文件。

crontab –e的时间用法说明;

* * * * * /etc/init.d/delete.sh

分 时 日 月 周 命令
第1列*号表示分钟1-59 每分钟用*或者 */1表示
第2列*号表示小时0-23小时(0表示0点)
第3列*号表示日期1-31日
第4列*号表示月份1-12月
第5列*号表示每周,0-6(0表示星期天)
第6列是要运行的命令

例如每周3的晚上23:30运行该脚本,可以这样写:

30 23 * * 3 /etc/init.d/delete.sh
Copy after login

The same is true for other time periods.

The above is the detailed content of Linux schedules automatic deletion of files in a directory at regular intervals. For more information, please follow other related articles on the PHP Chinese website!

source:linuxprobe.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template