我试图读取一个包含以下内容的文本fiie sport.txt,并尝试将用户输入与文本文件中的运动名称匹配,
如果找到它,它会打印“找到运动”,如果找不到它,它会打印“没有找到运动”
显示的第一个示例看起来几乎完美,直到我尝试输入一个随机单词时,它显示一个错误
[:=:需要一元运算符
我也试过在第二个例子中为变量添加“”但是它只会打印“没有找到运动”,即使我在文本文件中输入了与运动名称完全匹配的运动名称
体育.txt

cycling
swimming
batmintion

代码(示例1)
#!/bin/bash
file="sports.txt"
read -p "Enter a sports name": sportsName
existingSports=$(grep $sportsName $file);
if [ $existingSports == $sportsName ]; then
     echo "Sports Found"
else
     echo "No Sports Found"
fi

如果我根据上面的密码输入“游泳”
输出
Sports Found

如果我输入“游泳”
输出
No Sports Found

如果我随便输入一个词“asd”
输出
[: ==: unary operator expected
No Sports Found

代码(示例2)
#!/bin/bash
file="sports.txt"
read -p "Enter a sports name": sportsName
existingSports=$(grep $sportsName $file);
if [ "$existingSports" == "$sportsName" ]; then
     echo "Sports Found"
else
     echo "No Sports Found"
fi

如果我根据上面的密码输入“游泳”
输出
No Sports Found

如果我输入“游泳”
输出
No Sports Found

代码(示例3)
#!/bin/bash
file="sports.txt"
read -p "Enter a sports name": sportsName
existingSports=$(grep $sportsName $file);
if [[ "$existingSports" == "$sportsName" ]]; then
     echo "Sports Found"
else
     echo "No Sports Found"
fi

如果我根据上面的密码输入“游泳”
输出
No Sports Found

如果我输入“游泳”
输出
No Sports Found

如前所述,第一个例子几乎接近。我该怎么做才能去掉错误消息?

最佳答案

而不是这个街区:

existingSports=$(grep $sportsName $file);
if [ $existingSports == $sportsName ]; then
     echo "Sports Found"
else
     echo "No Sports Found"
fi

您可以利用grep -q和单词边界,并将代码缩减为单行:
grep -q "\<$sportsName\>" "$file" && echo "Sports Found" || echo "No Sports Found"

根据man grep
-q, --quiet, --silent
Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected.

关于bash - [:==:一元运算符期望值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19630619/

10-10 18:58