rm -fr *
不会删除.files
另一方面
rm -fr * .*
会删除太多!
有没有可靠的方法来递归删除 Bash 中目录的所有内容?
我能想到的一种方法是:
rm -fr $PWD
mkdir $PWD
cd $PWD
这具有暂时删除$PWD
的副作用。
我建议先使用:
shopt -s dotglob
dotglob
:如果设置,bash 在路径名扩展的结果中包含以.
开头的文件名
rm -fr * .*
相对"安全"。 rm
被POSIX禁止对.
和..
采取行动。
rm -rf . ..
将是一个无操作,尽管它将返回 1。如果您不希望返回错误,可以执行以下操作:
rm -rf .[!.]*
这是POSIX标准化的,不需要bash扩展。
您还可以使用查找:
find . -delete
您可以将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.
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 ..?*
我们需要避免包含星号的参数来解决此问题。