当某些脚本在其中执行 grep 时编辑文件是否有任何影响

Does editing a file while some script is performing grep in it has any effect

好吧,我正在尝试根据文件中不存在的某些文本做出一些决定,但问题是当我的 shell 脚本在其中执行 grep 时文件将被修改。

#!/bin/bash
grep -q "decision" /home/tejto/test/testingshell
ret_code=$?
while [ $ret_code -ne 0 ]
do
  echo $ret_code
  grep -q "decision" /home/tejto/test/testingshell
  echo 'Inside While!'
  sleep 5
done
echo 'Gotcha!'

启动此 shell 脚本时文件中不存在文本 "decision",但是当我通过其他 bash 提示修改此文件并将文本 'decision' 在其中,在这种情况下,我的脚本没有进行该更改,并且在 while 中继续循环,所以这是否意味着我的 shell 脚本缓存了该特定文件?

因为您只在循环外设置了一次 ret_code 变量,而不是在下一个 grep -q 命令后在循环内再次设置它。

要修复您需要:

grep -q "decision" /home/tejto/test/testingshell
ret_code=$?
while [ $ret_code -ne 0 ]
do
  echo $ret_code
  grep -q "decision" /home/tejto/test/testingshell
  ret_code=$?
  echo 'Inside While!'
  sleep 5
done
echo 'Gotcha!'

或者您可以这样缩短脚本:

#!/bin/bash

while ! grep -q "decision" /home/tejto/test/testingshell
do
  echo $?
  echo 'Inside While!'
  sleep 5
done
echo 'Gotcha!'

即无需使用变量并直接在 while 条件中使用 grep -q

[EDIT:Tejendra]

#!/bin/bash

    until grep -q "decision" /home/tejto/test/testingshell
    do
      echo $?
      echo 'Inside While!'
      sleep 5
    done
    echo 'Gotcha!'

最后一个解决方案不会使用 ret_code 并给出所需的结果作为第一个解决方案。