bash 使用 find 删除所有子目录(及其文件)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5896223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:56:47  来源:igfitidea点击:

Using find to delete all subdirectories (and their files)

bashrecursionfindsubdirectoryrm

提问by infmz

I'm sure this is straight forward and answered somewhere, but I didn't manage to find what I was looking for. Basically, I'm trying to run a cron script to clear the contents of a given directory every 7 days. So far I have tried the following,

我确定这是直截​​了当的并在某处回答,但我没能找到我想要的东西。基本上,我试图运行一个 cron 脚本来每 7 天清除一次给定目录的内容。到目前为止,我已经尝试了以下,

find /myDir -mtime 7 -exec rm -rf {} \;

This however also deletes the parent directory myDir, which I do not want. I also tried,

但是,这也会删除我不想要的父目录 myDir。我也试过,

find /myDir -type f -type d -mtime 7 -delete

which appeared to do nothing. I also tried,

这似乎什么也没做。我也试过,

fnd /myDir -type d -delete

which deleted all but the parent directory just as I need. However, a warning message came up reading,

根据我的需要删除了除父目录之外的所有目录。然而,一条警告信息出现了,

relative path potentially not safe

相对路径可能不安全

I'd appreciate if anyone can rectify my script so that it safely deletes all subdirectories in folder.

如果有人可以纠正我的脚本,以便它安全地删除文件夹中的所有子目录,我将不胜感激。

Many thanks. =)

非常感谢。=)

UPDATE:I decided to go for the following,

更新:我决定进行以下操作,

find /myDir -mindepth 1 -mtime 7 -delete

Based upon what I learned from all who replied. Again, many thanks to you all.

根据我从所有回复的人那里学到的。再次,非常感谢你们所有人。

采纳答案by linuts

Try:

尝试:

find /myDir -mindepth 1 -mtime 7 -exec rm -rf {} \;

回答by MarcoS

What about

关于什么

cd myDir/ ; find . -type d -delete

assuming that you run this from myDirparent directory.

假设您从myDir父目录运行它。

If you can't guarantee myDir exists, then this is safer:

如果你不能保证 myDir 存在,那么这更安全:

cd myDir/ && find . -type d -delete

回答by Bobby Impollonia

find /myDir -mindepth 1 -mtime 7 -delete

find /myDir -mindepth 1 -mtime 7 -delete

should probably be

应该是

find /myDir -mindepth 1 -mtime +7 -delete

find /myDir -mindepth 1 -mtime +7 -delete

(or maybe mtime +6). The +means things 7 days old or older rather than exactly 7 days.

(或者也许mtime +6)。这+意味着 7 天或更早的事情,而不是 7 天。