删除目录内容的正确方法

Dor*_*Dor 6 filesystems rm

在没有所述目录的情况下删除目录的所有内容的正确方法是什么?
例如,我有以下目录结构:

foo/
    bar1/
    bar2/
    x.txt
Run Code Online (Sandbox Code Playgroud)

我想删除文件夹bar1bar2文件x.txt而不删除 foo.

还请考虑带有特殊字符的文件名,这些字符可能会被忽略或引发错误。


编辑 #1(UTC 时间 9 月 30 日,18:26):
我认为我的问题不是这个问题的重复,因为我要求删除目录中的所有内容,而另一个问题没有,答案也没有t 包括这样的解决方案。

slm*_*slm 9

如果您知道目录,则可以使用以下命令之一:

$ find foo/* -delete

$ rm -fr foo/*

$ find foo/* -exec rm -fr {} +
Run Code Online (Sandbox Code Playgroud)

如果您有以点 ( .)开头的文件,那么您需要修改版本的rm.

$ rm -fr foo/{*,.*}
Run Code Online (Sandbox Code Playgroud)

例子

$ ls -l foo
drwxrwxr-x    6 saml saml  4096 Sep 27 09:43 .
drwx------. 263 saml saml 32768 Sep 27 09:42 ..
drwxrwxr-x    2 saml saml  4096 Sep 27 09:43 dir1
drwxrwxr-x    2 saml saml  4096 Sep 27 09:43 dir2
drwxrwxr-x    2 saml saml  4096 Sep 27 09:43 dir space1
drwxrwxr-x    2 saml saml  4096 Sep 27 09:43 dir space2
-rw-rw-r--    1 saml saml     0 Sep 27 09:43 .dot space1
-rw-rw-r--    1 saml saml     0 Sep 27 09:43 .dot space2
-rw-rw-r--    1 saml saml     0 Sep 27 09:43 file1
-rw-rw-r--    1 saml saml     0 Sep 27 09:43 file2
-rw-rw-r--    1 saml saml     0 Sep 27 09:43 file space1
-rw-rw-r--    1 saml saml     0 Sep 27 09:43 file space2

$ rm -fr foo/{*,.*}
rm: cannot remove directory: `adir/.'
rm: cannot remove directory: `adir/..'
$

$ ls -l foo/
total 0
$
Run Code Online (Sandbox Code Playgroud)

重复一个新的文件目录:

$ find foo/* -delete
$
Run Code Online (Sandbox Code Playgroud)

处理特殊字符

如果您有一个名为foo tastic有空格的目录,您可以引用它但仍使用通配符:

例子

$ rm -fr "foo tastic"/*
Run Code Online (Sandbox Code Playgroud)

特殊的角色

在运行它们之前,我会经常使用这个技巧来查看 shell 对我的文件名组合的看法。在我上面使用的示例目录中:

$ ls -1 "文件"* 文件空间1 文件空间2

$ ls -1d "dir "* dir space1 dir space2

通过事先进行这些测试,您可以了解使用包含 glob 的命令时将运行哪些文件/目录。