在 Shell 脚本中使用 grep 和 if 语句

Pth*_*guy 2 grep shell-script

我想在一个文件中搜索一个字符串,在这个网站上搜索了很多次之后,我最终使用了grepin 和if语句。然而,事情并没有像我期望的那样工作,即使我遵循了我在其他相关帖子中找到的所有说明。这是我的代码。

echo "Enter dicounter number"
read string1
echo "Enter side with LEDs"
read string2

if grep -q "dicounter_$string1_from_$string2" MasterFile.txt; then
   echo "dicounter_$string1_from$string2 already exists in MasterFile."
else
   { (a bunch of stuff to make the transmitter operate) }
fi
Run Code Online (Sandbox Code Playgroud)

我认为的主要问题是我在命令行参数中的阅读方式。

Dop*_*oti 7

如果脚本没有按预期工作,您可能想要尝试的第一件事是set -x在代码中的麻烦位置之前添加(在本例中,在 之前grep),然后运行脚本。然后您将看到脚本实际在做什么,以便您可以将其与您期望它做的事情进行比较。

在您的情况下,问题可能是_变量名称中的有效字符,因此您尝试使用的值$string1_from_而不是$string1您期望的值。这就是为什么即使不使用花哨的操作,将变量名括在花括号中也是一种很好的做法。例如:

if grep -q "dicounter_${string1}_from_${string2}" MasterFile.txt; then
   echo "dicounter_${string1}_from${string2} already exists in MasterFile."
else
   [..]
Run Code Online (Sandbox Code Playgroud)

  • 语法高亮编辑器也是发现此类问题的好工具,尽管它们可能只是用一种颜色高亮整个引用的字符串。shellcheck.net 警告未设置的变量,但... (2认同)