rm -fr *
不会删除.files
另一方面,
rm -fr * .*
会删除太多内容!
在Bash中,有可靠的方法来递归删除目录中的所有内容吗?
我能想到的一种方法是:
rm -fr $PWD
mkdir $PWD
cd $PWD
这会有一个副作用,即临时删除
$PWD
。我建议首先使用以下方法:
shopt -s dotglob
dotglob
:如果设置了此选项,bash会在路径名扩展结果中包含以.
开头的文件名。
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 ..?*
我们需要避免包含星号的参数来解决这个问题。
rm -fr * .*
相对来说是“安全”的。rm
被POSIX禁止作用于.
和..
。
rm -rf . ..
这将是一个空操作,但它会返回1。如果您不想要错误返回,可以这样做:
rm -rf .[!.]*
find . -delete