简体   繁体   English

Unix shell 循环检查一个目录是否存在于多个目录中

[英]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.没有 output == 没有找到目录,什么也没做。

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此处提供完整的讨论和解决方案: https://mywiki.wooledge.org/BashFAQ/001

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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