for 循环没有在 sh 中给出预期的输出,而如果将 sh """#!/bin/bash +x 添加到脚本块,它工作正常

for loop is not giving expected output in sh whereas it is working fine if sh """#!/bin/bash +x is added to the script block

for newfile in `find . -type f ! -path "./data/*" ! -name new_changes.txt`; do 
     if ! grep -q "$newfile" new_changes.txt; then 
       rm $newfile;
     fi
done

如果在代码块的开头给出 sh """#!/bin/bash +x,则上述代码可以正常工作。但是当它被注释掉时 - 它会抛出以下错误

rm: cannot remove '$newfile': No such file or directory

关于我们如何修改此 for 循环以在没有 sh """#!/bin/bash +x 的情况下工作的任何建议?

@alaniwi 已经在他的评论中解释了您的 rm 命令中的错误。您正在尝试删除名称为 $newfile 的文件,并且您可能没有任何以美元符号开头的文件。

另一个问题类似,但不完全相同:您的 grep 命令搜索 文字 字符串 $newfile,而您可能想要搜索存储在 variable 新文件中的字符串。因此,您必须删除 \

但这仍然意味着变量newfile的内容需要作为正则表达式进行解释。例如,如果 newfile 的值为 abc.txt,如果 new_changes.txt 仅包含 abcdtxtgrep 也会成功。为避免此错误,您应该使用 -F 选项来进行 grep,以避免被解释为正则表达式。

还有一个错误:假设 newfile 的值为 abc,而 new_changes.txt 只包含 xxxabc,但它们仍然匹配,因为abcxxxabc 的子串。为避免此错误,您应该对 grep 使用 -x 选项,这会强制匹配整行。

因此,您的命令应该是 grep -qFx "$newfile" new_changes.txt