我想比较用户在这个文本文件中输入的内容,以确定他们输入的内容是否在文本文件中,然后告诉他们。
文件1:color_readme.txt在这个文件中是:
red
red
orange
blue
代码:
echo Please enter a color:
cat color_readme.txt (printing the colors to screen)
read userinput (read what the user enters)
variable1 = grep $userinput (a random variable = what is found in the file according to what the user typed)
if userinput = variable1 (SAY THIS)
else (SAY THIS)
对于初学者来说,最好的方法是什么?我的老师只希望我使用基本的if-else和else条件。
echo "Pick one of the colours below:"
cat colour_readme.txt
read i
if x=$(grep "$i" colour_readme.txt)
then echo "You picked $i and it appears in colour_readme.txt as $x"
else echo "You picked $i but it does not appear in colour_readme.txt"
fi
您可以在不使用test
(或[
或[[
)运算符的情况下测试命令的状态;它们只是返回可由if
测试的退出状态的特殊命令。
echo "name a color"
read i
grep -q $i color.txt
if [ $? == 0 ]
then
echo "$i is in the file"
else
echo "$i is not in the file"
fi
"if[$?==0]"测试上一个命令的退出状态,在本例中是grep。如果grep找到某个东西,它的退出状态将为0,如果没有,则退出状态为1。
answer="Wrong"
realcolour=`cat ./color_readme.txt`
Until [ $answer = "Correct" ] ; Do
echo -n "Please enter a colour:"
read usercolour
If [ $usercolour = $realcolour ] ; Then
answer="Correct"
Else
answer="Wrong"
Fi
echo $answer
Done
编辑:…以上是在OP澄清文本文件中的多种颜色之前写的。。。