0

我有一个非常简单的 bash 脚本,它应该 grep 一个文件以查找我想要标记的多个短语。

它一直有效,但是当我想用 grep 查找“ print ”或“ puts ”时,我会摔倒(注意单词前后的空格)。

grep 忽略输入中的空格。

这是我的代码(不相关的内容已被删除)

#!/bin/sh

bad_phrases=('console.log(' 'binding.pry' ':focus,' 'alert(' ' print ' ' puts ')
bad_phrase_found=false

FILE='my_test_file.txt'

for bad_phrase in ${bad_phrases[*]} ; do
  if grep -q "$bad_phrase" $FILE ; then
      bad_phrase_found=true
      echo "A '$(tput bold)$(tput setaf 1)$bad_phrase$(tput sgr0)' was found in $(tput bold)$(tput setaf 5)$FILE$(tput sgr0)"
  fi
done

if $bad_phrase_found ; then
  exit 1
fi

exit 0

我已经研究过将 IFS 设置为 '~' 并以这种方式拆分数组,但这完全杀死了 grep 命令。

脚本的示例输出是;

在 my_test_file.txt 中找到“打印”

任何帮助将不胜感激。

4

1 回答 1

2

你需要使用"${bad_phrases[@]}". 不要忘记双引号。您应该始终养成引用所有变量的习惯,以抑制分词

for bad_phrase in "${bad_phrases[@]}" ; do
  if grep -q "$bad_phrase" "$FILE" ; then
      bad_phrase_found=true
      echo "A '$(tput bold)$(tput setaf 1)$bad_phrase$(tput sgr0)' was found in $(tput bold)$(tput setaf 5)$FILE$(tput sgr0)"
  fi
done
于 2013-04-25T08:39:33.993 回答