linux 开机自动删除/tmp目录下的文件

linux 开机自动删除/tmp目录下的文件


1:  查看/etc/default/rcs文件:  cat  /etc/default/rcs


#
# /etc/default/rcS
#
# Default settings for the scripts in /etc/rcS.d/
#
# For information about these variables see the rcS(5) manual page.
#
# This file belongs to the "initscripts" package.

# delete files in /tmp during boot older than x days.
# '0' means always, -1 or 'infinite' disables the feature
TMPTIME=0

# spawn sulogin during boot, continue normal boot if not used in 30 seconds
SULOGIN=no

# do not allow users to log in until the boot has completed
DELAYLOGIN=no

# assume that the BIOS clock is set to UTC time (recommended)
UTC=yes

# be more verbose during the boot process
VERBOSE=no

# automatically repair filesystems with inconsistencies during boot
FSCKFIX=no


注意红色部分的信息,即可明白


2、根据上述信息,修改 TMPTIME的值即可:

TMPTIME=-1


Linux中,你可以创建一个文件并在脚本中设置定时任务,使其在下次系统启动自动删除。下面是一个基本步骤: 1. **创建临时文件**: 首先,使用`mktemp`或`tempfile`创建一个临时文件,例如: ```bash FILE=$(mktemp /tmp/my_temp_file.XXXXXX) echo "Content goes here" > $FILE ``` 这将创建一个名为`my_temp_file.XXXXXX`的文件,内容是你想要添加的。 2. **添加自删除机制**: 可以使用`crontab`(定时任务计划)来设置文件在特定时间删除。比如你想让文件在下一次系统启动时被删除,你可以选择在`rc.local`文件中添加一行命令去删除它,因为`rc.local`在系统启动后运行。然而,由于`rc.local`并不支持定时任务,我们需要借助其他工具如`sh`脚本或者`systemd`服务。 - **使用`systemd`服务**: 编辑`/etc/systemd/system/myservice.service`文件,加入类似这样的内容: ```ini [Unit] Description=Delete Temporary File on Boot Before=multi-user.target [Service] ExecStart=/bin/bash -c 'rm "$FILE"' RemainAfterExit=true [Install] WantedBy=multi-user.target ``` 然后运行`sudo systemctl enable myservice`启用服务,`sudo systemctl start myservice`立即运行删除动作。 - **使用脚本**: 创建一个简单的shell脚本,如`delete_temp.sh`,然后添加到`/etc/cron.daily`目录(假设你想在每天开机删除): ```bash #!/bin/sh rm "$FILE" ``` 授予执行权限 (`chmod +x delete_temp.sh`),然后让它生效(`sudo update-crontab -u root -f` 或手动编辑`/etc/crontab`添加`@daily delete_temp.sh`)。 请注意,这种方法并不保证文件一定会在下次系统启动时立即删除,因为依赖于系统的启动顺序和其他进程运行情况。如果你想确保文件启动时立即删除,可能需要更复杂的解决方案。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值