linuxshellunixcommand-linecp

Unix shell loop to check if a directory exists inside multiple directories


I have folder structure like this:

/home/
   /folder1/
      /backup/
   /folder2/
      /backup/
   /folder3/
   /folder4/
      /backup/
   /folder5/

(As you can see, not all folder directories have a subdirectory backup)

I need to check if the directory backup exists in the folders 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. What can I try next?


Solution

  • 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