【问题标题】:bash loop through all find recursively in sub-directoriesbash循环遍历所有子目录中的递归查找
【发布时间】:2012-03-10 07:42:30
【问题描述】:

我有一个如下所示的 bash 脚本:

#!/bin/bash
FILES=public_html/*.php  # */ stupid syntax highlighter!
for f in $FILES
do
  echo "Processing $f file..."
  # take action on each file.
done

现在我需要它遍历 public_html 中的所有子目录,所以它应该运行:

/public_html/index.php
/public_html/forums/status.php
/public_html/really/deep/file/in/many/sub/dirs/here.php

为了做到这一点,我应该将FILES=public_html/*.php 更改为什么?

我还需要检查以确保至少有一个文件,否则它会打印出来

Processing *.php file...

【问题讨论】:

    标签: bash shell for-loop


    【解决方案1】:
    FILES=$(find public_html -type f -name '*.php')
    

    重要提示:注意*.php 周围的单引号,以防止* 的外壳扩展。

    【讨论】:

    • 它只返回密码的结果。
    • 我不这么认为。 (你使用 GNU 的 find 吗?)mkdir -p public_html/{a,b,c}; touch public_html/{a,b,c}/{1,2,3}.php; find public_html -type f -name *.php 返回所有 9 个文件。
    • 这工作FILES="$(find public_html -type f -name '*.php')"
    • 您可能在某些文件名中有空格,在整个文件中加上引号会引用每个单独的匹配项。
    • 另外,$() 表示在大括号内运行命令并从结果的标准输出中生成一个字符串。
    【解决方案2】:
    FILES=`find public_html -type d`
    

    $FILES 现在将是 public_html 中每个目录的列表。

    【讨论】:

    • 我认为您误解了这个问题。我需要获取目录中的文件,而不是目录本身
    • 您想要public_html 子目录中的每个php 文件吗?在这种情况下你可以写find public_html -name *.php
    猜你喜欢
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    相关资源
    最近更新 更多