递归删除文件夹和子文件夹中的文件

时间:2019-02-08 15:31:33

标签: bash shell

我想递归删除文件夹及其子文件夹中包含的所有文件,而不删除文件夹。

例如,我具有以下结构:

MainFolder
│   Somefile6
│   Somefile7
│ 
└───child1
│   |   Somefile
│   |   Somefile2
│   │   
│   └───child2  
│       │   Somefile3
│       │   Somefile4
│       │
│       └───child3
│           │   Somefile5

运行bash脚本后(我尝试过):

#!/bin/bash
shopt -s nullglob dotglob # Include hidden file
dir=(/root/some/path/*)
if [ ${#dir[@]} -gt 0 ]; then
    for file in "$dir"
    do
        echo "Doing some custom action before deleting..."
        echo "Deleting $file"
        rm "$file"
        sleep 1
    done
else
    echo "The folder is empty";
fi

我希望获得的东西

MainFolder
│ 
└───child1
│   │   
│   └───child2  
│       │
│       └───child3
│           │   

问题:

它只是删除文件Somefile6Somefile7

1 个答案:

答案 0 :(得分:2)

您可以使用find查找所有文件并将其删除:

find -type f -delete
  • -type f:告诉find仅产生文件
  • -delete:告诉find 删除所有找到的项目

如果您不想删除文件,则可以使用-exec并使用文件find进行所需的操作。