简体   繁体   中英

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, 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM