dountil() {
#Prompt user below to guess randomly-generated number between 1 and 10
(( answer = $RANDOM % 1-10 ))
until [[ $guess -eq answer ]]
do
read -p "Enter a number between 1 and 10:" guess
if [[ $guess -ne answer ]]; then
echo "Incorrect. Try again"
elif [[ $guess -eq answer ]]; then
echo "Correct! Want to play again?"
read -p prompt
if [[ $prompt = yes ]]
dountil
if [[ $prompt = no ]]
then
echo "Goodbye."
fi
};
这几天我一直在试图解决这个问题,但几乎每次都碰壁。我已经修复了一些错误,但随后又出现了新的错误。就像现在一样,我得到
意外标记“}”附近出现语法错误
任何帮助将不胜感激!
答案1
始终以正确的缩进编写代码。问题很明显...
dountil () {
(( answer = $RANDOM % 1-10 ))
until [[ $guess -eq answer ]]
do
read -p "Enter a number between 1 and 10:" guess
if [[ $guess -ne answer ]]; then
echo "Incorrect. Try again"
elif [[ $guess -eq answer ]]; then
echo "Correct! Want to play again?"
read -p prompt
if [[ $prompt = yes ]]
dountil
if [[ $prompt = no ]]
then
echo "Goodbye."
fi
}
至少有两个then
,两个fi
和一个done
失踪。然后从内部再次调用该函数,那是什么?
根据您的编码水平,您实际上应该一次仅添加一两个命令,然后运行新版本的脚本。只是为了轻松捕获语法问题。
避免递归
无论如何都不需要函数
while true; do
# ...
if [[ $prompt != yes ]]; then
break
fi
done
使函数成为循环
dountil () {
while true; do
# ...
if [[ $prompt != yes ]]; then
break
fi
done
}
只将核心代码放入函数中
guess_number () {
(( answer = $RANDOM % 1-10 ))
read -p "Enter a number between 1 and 10: " guess
if [[ $guess -ne answer ]]; then
echo "Incorrect."
else
echo "Correct."
fi
}
while true; do
guess_number
# ...
if [[ $prompt != yes ]]; then
break
fi
done