尝试编写一个脚本来玩猜谜游戏。脚本应该生成一个数字并请求用户猜测。然后,该脚本将比较用户输入的数字与生成的数字,它应确保游戏继续,直到用户请求怜悯或正确猜测数字。它应该向用户提供更高或更低的提示以帮助他们。一旦获胜条件之一发生,用户应该以某种方式表示祝贺,然后脚本应该结束。如果用户请求怜悯,它应该回显一个不同的短语。
#!/bin/sh
number="$(( ( RANDOM % 100 ) + 1 ))"
echo "Guess a number between 1 and 100, or say 'mercy'"
read answer
until [[ $answer -eq $number || $answer -eq "mercy" ]]
do
if [ $answer -lt $number ]
then
echo "Guess higher"
read answer
else
echo "Guess lower"
read answer
fi
done
if [ $answer -eq "mercy" ]
then
echo "You are a quitter"
else
echo "CONGRATS"
fi
每次你猜对了,或者只是说出怜悯和错误代码:line 19: [: mercy: integer expression expected
答案 0 :(得分:1)
您正在使用-eq
进行字符串比较; -eq
用于整数比较 - 您需要使用=
或==
。这就是你得到错误的原因。
此外,/bin/sh
不一定是bash。因此,请将#!/bin/bash
用作shebang。
#!/bin/bash
number="$(((RANDOM % 100) + 1))"
echo "Guess a number between 1 and 100, or say 'mercy'"
read answer
until [[ $answer -eq $number || $answer == "mercy" ]]
do
if [[ $answer -lt $number ]]
then
echo "Guess higher"
read answer
else
echo "Guess lower"
read answer
fi
done
if [[ $answer == "mercy" ]]
then
echo "You are a quitter"
else
echo "CONGRATS"
fi
除非您打算将此脚本移植到其他POSIX shell,否则我建议您使用[[ .. ]]
而不是[ .. ]
。见What is the difference between test, [ and [[ ?
答案 1 :(得分:0)
我会使用类似的东西:
#!/bin/bash
number="$(( ( RANDOM % 100 ) + 1 ))"
steps=0
while :
do
read -r -p "Guess a number between 1 and 100, or say 'mercy'> " answer
case "${answer,,}" in
[0-9]|[0-9][0-9]) let steps++ ;;
mercy) echo "Quitter after $steps steps" ; exit 0;;
*) echo "Don't understand the $answer" ; continue ;;
esac
case 1 in
$(( answer < number )) ) echo "Guess higher" ;;
$(( answer > number )) ) echo "Guess lower" ;;
$(( answer == number )) ) echo "winner in $steps steps" ; exit ;;
esac
done