grep 与 inotifywait 结合使用时表现异常

grep behaves strange in combination with inotifywait

我很难理解 grep return 值的某种异常。

如 grep 手册页所述,return 值在匹配的情况下为零,在 no-match/error/etc 的情况下为非零。

在此代码中:(bash)

inotifywait -m ./logdir -e create -e moved_to |
  while read path action file; do
    if grep -a -q "String to match" "$path/$file"; then
      # do something  
    fi
  done

匹配时return非零。

在此代码中:(bash)

search_file()
{
  if grep -a -q "String to match" ""; then
    # do something
  fi
}

inotifywait -m ./logdir -e create -e moved_to |
    while read path action file; do
      search_file "$path/$file"
    done

匹配时return为零。

谁能给我解释一下这是怎么回事?

编辑: 让我再次明确:如果我 运行 包含字符串的文件中的第一个代码,则 if 语句是 运行ning。如果我 运行 同一文件中的第二个代码,则 if 语句失败并且不会 运行。

我支持@John1024's conjecture that he wrote as a

"anomaly" 可能是由于您的脚本的两个版本之间存在细微的时间差异。在 create 事件的情况下,文件最初是空的,因此 grep 将开始扫描部分写入的文件。通过函数调用 grep 会引入一个小的延迟,这会增加在 grep 打开文件时搜索到的数据出现在文件中的机会。

此竞争条件的解决方案取决于几个 assumptions/requirements:

  • 你能假设监视目录中预先存在的文件不会被修改吗?

  • 您是要尽快识别每个新的匹配文件,还是可以延迟处理直到关闭?