1

I want to delete all files contained in a folder and his subfolder recursively without deleteing folders.

For example I have this structure :

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

After running a bash script (what I tried) :

#!/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

What I expect to obtain

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

Problem:

It's just deleting the files Somefile6 and Somefile7

executable
  • 3,365
  • 6
  • 24
  • 52

1 Answers1

2

You can use find to look for all files and let it delete those:

find -type f -delete
  • -type f: tells find to only yield files
  • -delete: tells find to delete all the found items

If you don't want to delete the files you can use -exec and do what ever you want with the files find yields.

tuxtimo
  • 2,730
  • 20
  • 29