在 mac os x 终端上,删除所有文件和文件夹的命令是什么?

在 mac os x 终端上,删除所有文件和文件夹的命令是什么?

在 Mac OS X 终端上,我们如何才能递归地删除除一个目录之外的所有文件和文件夹(包括隐藏文件)?

谢谢。

答案1

警告:运行任何命令来递归删除文件都是危险的。在盲目运行此类危险命令之前,请务必进行测试,并且绝不永远以 root 用户身份(或使用 sudo 等)运行它们。

使用一些 bash 相对容易做到这一点,如果您要经常这样做,甚至可以将其作为传递的参数。但是,如果只是一次性尝试,请尝试下面我的简单测试。

首先,我将创建一些文件夹用于测试:

cd test; mkdir -p one two three four five six .hidden

然后,我将创建一个 bash 脚本(在本例中为 rm.bash),其内容如下:

for i in `ls -A`
do      
        if [ ! "${i}" == 'three' ] && [ ! "${i}" == $0 ]; then 
                echo "would delete ${i}" 
        else    
                echo "not deleting ${i}" 
        fi
done

解释一下:ls -A将打印除当前文件夹和父文件夹(...)之外的所有文件。我们用循环使用此列表for来遍历所有内容。我(任意)决定我们留下的唯一文件夹是“three”,并且我不想删除脚本rm.bash本身。

因此,if只要所讨论的文件/文件夹没有被命名为“或three”,条件才会为真rm.bash$0意味着无论您如何称呼文件,这都会起作用)。

我没有立即运行它rm -rf ${i}(这很危险),而是使用了几个echo命令来显示哪些会被删除,哪些不会。

这是我的示例输出:

would delete five
would delete four
would delete one
not deleting rm.bash
would delete six
not deleting three
would delete two

一旦您验证了脚本正在采取正确的操作,没有删除不应该删除的内容等,那么您可以将代码更改为:

for i in `ls -A`
do      
        if [ ! "${i}" == 'three' ] && [ ! "${i}" == $0 ]; then 
                rm -rf ${i} 
        fi
done

答案2

另一种选择。与@Adam C 的答案相同的注意事项;未经测试请勿运行。

一些演示数据:

$ mkdir testing; cd testing
$ mkdir one two three four "fi ve"
$ touch one/one.txt two/two.txt three four/keep.txt fi\ ve/.hidden

模拟删除除四个之外的所有/

$ find . -mindepth 1  -path ./four -prune -o -exec echo would remove "{}" +

输出:

would remove ./fi ve ./fi ve/.hidden ./two ./two/two.txt ./one ./one/one.txt ./three

笔记:

-mindepth 1  prevents including /.
Prune removes path four/ from processing, or...
-o means "or" (either prune the left, or exec on the right)
High speed / low resource use:
  find will stop processing a tree once pruned (no wasted operations)
  One xargs-style list is built (with +), removal happens in one command.
  To process one at a time, replace + with \;
Spaces are handled correctly within " "
-delete is shorter but may not operate on directories
find won't follow symlinks by default

相关内容