我想比较用户输入到此文本文件的内容,以确定他们输入的内容是否在文本文件中,然后告诉他们。
file1: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 ifelse和else条件。
答案 0 :(得分:4)
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
进行测试。
答案 1 :(得分:2)
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澄清文本文件中的多种颜色之前写的......
答案 2 :(得分:2)
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。