如何可靠地执行rm -fr *命令?

3
rm -fr *

不会删除.files

另一方面,

rm -fr * .*

会删除太多内容!

在Bash中,有可靠的方法来递归删除目录中的所有内容吗?

我能想到的一种方法是:

rm -fr $PWD
mkdir $PWD
cd $PWD

这会有一个副作用,即临时删除$PWD

只要dir不是当前工作目录,那么“rm -rf dir”就是好的。 - codeforester
将来参考,这更适合于unix.stackexchange.com - Josh Kelley
4个回答

6

我建议首先使用以下方法:

shopt -s dotglob

dotglob:如果设置了此选项,bash会在路径名扩展结果中包含以 . 开头的文件名。


1
您可以使用 find 命令的 -delete-maxdepth 参数:
find . -name "*" -delete -maxdepth 2

假设你现在在目录temp下,目录结构如下:

./temp
     |_____dir1
     |        |_____subdir1
    X|_file  X|_file      |_file
     |
    X|_____dir2
             X|_file

看树形结构中,带有X标记的文件和目录将会被使用上述命令删除。由于subdir1内有一个文件,且find设置了最大深度为2,因此它得以幸免。find会删除以.开头的文件,但对符号链接无效。
 -delete
         Delete found files and/or directories.  Always returns true.
         This executes from the current working directory as find recurses
         down the tree. It will not attempt to delete a filename with a
         ``/'' character in its pathname relative to ``.'' for security
         reasons. Depth-first traversal processing is implied by this
         option. Following symlinks is incompatible with this option.

1

在UNIX系统中,通常使用以下方式:

rm -rf * .[!.]* ..?*

这将列出以点号或双点号开头的所有文件(但不包括纯双点号(./..)。

但如果该类型文件不存在,该通配符扩展将保留星号。

让我们进行测试:

$ mkdir temp5; cd temp5
$ touch {,.,..}{aa,bb,cc}
$ echo $(find .)
. ./aa ./cc ./..bb ./..aa ./.cc ./.bb ./..cc ./.aa ./bb

而且,正如所示,这将包括所有文件:
$ echo * .[!.]* ..?*
aa bb cc .aa .bb .cc ..aa ..bb ..cc

但如果其中一种类型不存在,星号将保留:

$ rm ..?*
$ echo * .[!.]* ..?*
aa bb cc .aa .bb .cc ..?*

我们需要避免包含星号的参数来解决这个问题。

1
rm -fr * .*

相对来说是“安全”的。rm被POSIX禁止作用于...

rm -rf . .. 

这将是一个空操作,但它会返回1。如果您不想要错误返回,可以这样做:

rm -rf .[!.]* 

"该功能符合POSIX标准,不需要使用bash扩展。"
"您还可以使用find命令:"
find . -delete 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接