目的是保存最新的 10 条记录,把多余的文件删除,在命令行中是可以运行的.但是放在 crontab 中就执行不了..
环境是 CentOS7, 麻烦能帮忙指出哪里有问题么?
* * * * * ls -rt /root/playground/linux/ | head -n -10 | xargs rm -f
还试了
* * * * * ls -rt /root/playground/linux/ | head -n -10 | xargs -d '\n' rm -f
目的是保存最新的 10 条记录,把多余的文件删除,在命令行中是可以运行的.但是放在 crontab 中就执行不了..
环境是 CentOS7, 麻烦能帮忙指出哪里有问题么?
* * * * * ls -rt /root/playground/linux/ | head -n -10 | xargs rm -f
还试了
* * * * * ls -rt /root/playground/linux/ | head -n -10 | xargs -d '\n' rm -f
|
x1596357May 25, 2021
1
常见的问题是 crontab 的环境中 PATH 是很干净的,最好用绝对路径,比如 head 用 /usr/bin/head 代替。然后 ls 是个内置函数,并不是个程序,所以你可以用 /usr/bin/bash -c "ls -rt /root/playground/linux/ | /usr/bin/head -n -10 | /usr/bin/xargs -d '\n' rm -f"代替
|
|
aladdindingdingMay 25, 2021
2
加载一下 PATH
|
|
christinMay 25, 2021 via iPhone
4
直接把这段命令放到根目录下运行一次看能运行不
|
|
tusjMay 25, 2021
6
要么 head -n 10
|
|
guaderMay 25, 2021
7
目录有权限吗
|
|
ksc010May 25, 2021
8
在命令 后面添加 >> /tmp/error.log 2>&1
|
|
BeebirdMay 25, 2021
9
楼主这个是删除最老的 10 个文件啊
|
|
BeebirdMay 25, 2021
10
没有指定工作目录,这样就可以了,虽然不知道楼主到底是要删除 10 个最老的,还是保留 10 个最新的。。。
* * * * * cd /root/playground/linux/ && ls -rt /root/playground/linux/ | head -n -10 | xargs rm -f |
|
BeebirdMay 25, 2021
11
看了下楼主 head -n -10 是对的 😂 我搞错了
|
|
harwckMay 25, 2021
12
8 楼为正解
|
|
QHKZMay 25, 2021
13
cron 有 log,看看 log 怎么说
|
|
hgc81538May 25, 2021
14
rm 要絕對路徑?
* * * * * ls -rt /root/playground/linux/ | head -n -10 | awk '{print "/root/playground/linux/" $0}' | xargs rm -f |
|
neilyooneMay 25, 2021
15
* * * * * 分别代表 分 /时 /日 /月 /周
你总要设定一个 crontab 执行的时间周期吧? 比如每分钟执行一次 */1 * * * * CMD |
|
16
@x1596357
首先 ls 不是内置函数。 https://packages.ubuntu.com/focal/amd64/coreutils/filelist 这里可以看到存在 /bin/ls 其次 cron 本来就会用 shell 来执行,就算 ls 是内置命令,也是没问题的。 https://github.com/mirror/busybox/blob/7de0ab21d939a5a304157f75918d0318a95261a3/miscutils/crond.c#L721 |
|
matrix67May 25, 2021
18
|
|
yEhwG10ZJa83067xMay 25, 2021
19
#4 按 4 楼直接先运行一遍命令能不能执行?
|
|
20
@christin 确实不行, ls -rt /root/playground/linux/ | head -n -10 这部分可以,但是后面删除没有生效.
|
|
21
@justrand 确实不行, ls -rt /root/playground/linux/ | head -n -10 这部分可以,但是后面删除没有生效.
|
|
lamesbondMay 25, 2021
23
看日志,好像是 /var/spool/mail/用户名
|
|
mangoDBMay 25, 2021
24
看下`man rm`,其中参数`f`有一段解释「 ignore nonexistent files, never prompt 」。
本应该暴露出来的问题被你隐藏了( doge )。 |
|
edsion996May 25, 2021
25
我建议可以尝试下只用 find 命令
|
|
snugloveMay 25, 2021
26
施展 cd 大法
* * * * * cd /root/playground/linux/ && ls -rt | head -10 | xargs rm -f 直接 find 查询删除最好 |
|
answerwaMay 25, 2021
27
看了一下上面的都稍微麻烦了,14 楼还加了一层 awk,试试这个
```bash * * * * * ls -rt /root/playground/linux/ | head -n -10 | xargs -i rm -f /root/playground/linux/{} ``` > 如果不加,crontab 在执行的时候是从根目录去删除,因为根目录没有这些文件,所以不会报错.. 另外补充一下,这里不是因为根目录没有这些文件不会报错,是因为 rm 加了 -f 参数,错误不会打印出来 |
|
jinliming2May 25, 2021
28
所以,直接这样呢:
* * * * * rm `ls -rtd /root/playground/linux/* | head -n -10` |
|
maxbonMay 27, 2021
30
很正常啊,你这路径不全,要写绝对路径,或者提前 cd 到相应目录做操作
|