I have folder structure like this:
/home/
/folder1/
/backup/
/folder2/
/backup/
/folder3/
/folder4/
/backup/
/folder5/
(As you can see, no all directories "folder" have a directory "backup")
I need to check if the directory "backup" exists in the "folder"s and delete it.
I am using this command:
for d in /home/* ;
do [ -d "$d/backup" ]
&& echo "/backup exists in $d"
&& rm -rf "$d/backup"
&& echo "/backup deleted in $d" ;
done
But it is not working. Please help.
CodePudding user response:
find . -type d -name "backup" -delete -print
Obviously, all content under backup directories will be lost.
This will recurse down into your directories. If you need to limit it to only the first level, you can do:
find . -maxdepth 1 -type d -name "backup" -delete -print
Both commands will print the deleted directories. No output == no directory found, nothing done.
Lastly, you want to avoid looping on files or directory names like you attempted, since you might have files or directories with spaces in their names. A complete discussion and solutions are available here: https://mywiki.wooledge.org/BashFAQ/001