在“find -exec”中执行“grep | xargs”时出现空行

CDu*_*Duv 8 shell grep find xargs

我正在尝试列出 Apache 通过.htaccess(包含deny from all)阻止的 Web 服务器的所有目录。我设法获得了阻塞列表,.htaccess但是当我尝试使用提取目录路径时,dirname出现了一些错误:

  1. .htaccess文件列表:

    find . -type f -name ".htaccess"
    ./.htaccess
    ./config/.htaccess
    ./files/.htaccess
    ./plugins/webservices/.htaccess
    ./plugins/webservices/scripts/.htaccess
    ./install/mysql/.htaccess
    ./scripts/.htaccess
    ./locales/.htaccess
    
    Run Code Online (Sandbox Code Playgroud)
  2. 阻塞.htaccess文件列表:

    find . -type f -name ".htaccess" -exec sh -c "grep -Eli '^deny from all$' '{}'" \;
    ./config/.htaccess
    ./files/.htaccess
    ./plugins/webservices/scripts/.htaccess
    ./install/mysql/.htaccess
    ./scripts/.htaccess
    ./locales/.htaccess
    
    Run Code Online (Sandbox Code Playgroud)
  3. 错误来了。与 2. 中的列表相同,但使用xargsdirname获取包含目录:

    find . -type f -name ".htaccess" -exec sh -c "grep -Eli '^deny from all$' '{}' | xargs dirname" \;
    dirname: missing operand
    Try dirname --help' for more information
    ./config
    ./files
    dirname: missing operand
    Try dirname --help' for more information
    ./plugins/webservices/scripts
    ./install/mysql
    ./scripts
    ./locales
    
    Run Code Online (Sandbox Code Playgroud)
  4. 列表 3 的调试尝试:我们可以看到 2 个空行,其中 2 个错误是:

    find . -type f -name ".htaccess" -exec sh -c "grep -Eli '^deny from all$' '{}' | xargs echo" \;
    
    ./config/.htaccess
    ./files/.htaccess
    
    ./plugins/webservices/scripts/.htaccess
    ./install/mysql/.htaccess
    ./scripts/.htaccess
    ./locales/.htaccess
    
    Run Code Online (Sandbox Code Playgroud)

这些 2 个空行显然与 2 个.htaccess被忽略的文件匹配,因为它们不包含deny from all. 我不明白为什么我在列表 3. 和 4. 中得到这些,但在 2. 中没有。

phe*_*mer 2

它失败是因为当 grep 不匹配时,您没有将任何内容传递给 xargs。

例如:

  1. find获取./.htaccess并调用您的-exec.
  2. grep与文件中的任何内容都不匹配,因此它不输出任何内容
  3. xargs启动时dirname没有任何参数,因此dirname认为它只是被滥用并显示其帮助消息。

执行此操作的正确方法:

find . -type f -name .htaccess -exec grep -iq '^deny from all$' {} \; -printf '%h\n'
Run Code Online (Sandbox Code Playgroud)