BASH 命令 - 在 DO - DONE 中使用 IF - FI

BASH command - using IF - FI within a DO - DONE

我正在尝试 运行 一个命令,该命令会找到 PHP 个包含 "base64_decode" and/or "eval" 的文件,回显文件名,顶部三行,如果文件包含超过 3 行,也是底部 3.

我现在有:

for file in $(find . -name "*.php" -exec grep -il "base64_decode\|eval" {} \;); do echo $file; head -n 3 $file; if [ wc -l < $file -gt 3 ]; then tail -n 3 $file fi; done | less

此returns以下错误:

bash: syntax error near unexpected token `done'

请帮忙:)

问题似乎出在这里:

if [ wc -l < $file -gt 3 ]; then

因为你需要在这里使用命令替换来确保wc -l命令先执行然后比较结果:

if [[ $(wc -l < "$file") -gt 3 ]]; then

您想执行您的 wc,更像是:

   if [[ $(wc -l < $file) -gt 3 ]]; then 

试试这个:

#!/bin/bash

for file in $(grep -H "base64_decode\|eval" ./*.php | cut -d: -f1);
do
        echo $file;
        head -n 3 $file;
        if [[ $(wc -l < $file) -gt 3 ]];
                then
                        tail -n 3 $file
                fi;
done

我测试过,似乎工作正常。

但是,请注意...如果 php 有 4 行,您将看到:

line1

line2

line3

line2

line3

line4

编辑:将上面的脚本更改为 grep inside files。

cat a.php
asdasd
asd
base64_decode
l
a

和结果

./test2.sh
./a.php
asdasd
asd
base64_decode
base64_decode
l
a

我会使用以下内容

while read -r file
do
        echo  ==$file==
        head -n 3 "$file"
        [[ $(grep -c '' "$file") > 3 ]] && (echo ----last-3-lines--- ; tail -n 3 "$file")
done < <(find . -name \*.php -exec grep -il 'base64_decode\|eval' {} \+)
  • for 上使用 while 更好,因为文件名可以包含空格。 /在这种情况下可能不是,但无论如何:)/
  • 使用 grep -c '' "$file" 有时会更好(当文件的最后一行不包含 \n 字符时(wc 计算 \n 字符文件)
  • \+ 代替 \;find 效率更高