简体   繁体   English

循环遍历Bash中的目录

[英]Looping through directories in Bash

I require the script to cd to a directory, then delete all but a few files in sub-directories—but leave the folders alone. 我要求脚本cd到一个目录,然后删除子目录中的所有文件,但保留文件夹。 Would it help to use switch / case s for each file I need to preserve? 对我需要保留的每个文件使用switch / case有用吗?

Ideally, I think it should keep searching for further sub-dirs, instead of me having nested loops which only search down two levels. 理想情况下,我认为它应该继续搜索更多的子目录,而不是我有嵌套循环,只搜索两个级别。

Another problem is that it skips folders with spaces (though this isn't an issue with the volumes that the script will run, for now). 另一个问题是它跳过带有空格的文件夹(虽然这不是脚本将运行的卷的问题,现在)。

Here's my code: 这是我的代码:

for i in /Users/YourName/Desktop/Test/* ; do
  if [ -d "$i" ]; then
    cd $i

    for j in "$i"/* ; do
      if [ -d "$j" ]; then
        cd $j

        for k in $(ls *); do
          if [ ! $k == "watch.log" ]; then
            echo $k
            rm -rf $k
          fi
        done

      fi
    done

  fi
done

You should use find : 你应该使用find

for i in $(find . -type d)
do
    do_stuff "$i"
done

If you really have a lot of directories, you can pipe the output of find into a while read loop, but it makes coding harder as the loop is in another process. 如果你真的有很多目录,你可以将find的输出传输到while read循环中,但是当循环在另一个进程中时,它会使编码变得更难。

About spaces, be sure to quote the variable containing the directory name. 关于空格,请务必引用包含目录名称的变量。 That should allow you to handle directories with spaces in their names fine. 这应该允许您处理名称中包含空格的目录。

How about this? 这个怎么样?

$ find /Users/YourName/Desktop/Test -type f -maxdepth 2 -not -name watch.log -delete


Explanation 说明

  • -type : look for files only -type :仅查找文件
  • -maxdepth : go down two levels at most -maxdepth :最多下降两级
  • -not -name (combo): exclude watch.log from the search watch.log -not -name (combo):从搜索中排除watch.log
  • -delete : deletes files -delete :删除文件


Recommendation 建议

Try out the above command without the -delete flag first. 首先尝试不使用-delete标志的上述命令。 That will print out a list of files that would have been deleted. 这将打印出已删除的文件列表。

Once you're happy with the list, add -delete back to the command. 一旦您对列表感到满意,请将-delete添加回命令。

Using find? 使用find? You can use several parameters, including depth, file age (as in stat), perms etc... 您可以使用多个参数,包括深度,文件年龄(如stat),烫发等...

find . -maxdepth 2

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

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