![sh 脚本中的“fi”错误](https://linux22.com/image/162418/sh%20%E8%84%9A%E6%9C%AC%E4%B8%AD%E7%9A%84%E2%80%9Cfi%E2%80%9D%E9%94%99%E8%AF%AF.png)
我一直在尝试在 Linux vi 中创建一个双骰子游戏,但我似乎无法弄清楚。我一直无法用“fi”结束我的“if”语句,说它是一个错误..这是为什么?我必须生成两个 1-6 之间的随机数,当它们相加时,你要么赢,要么输,要么得一分。这里有什么帮助吗?
这是我一直在尝试的:
# craps.sh program inn bash shell
# $RANDOM returns a different random integer at each invocation.
# generate_random_number function which returns sum of
# 2 random number between 1 and 6
generate_random_number()
{
RANGE=6
#get 2 random numbers
number1=$RANDOM
number2=$RANDOM
# get it between 1 and 6
number1=$((($number1%$RANGE)+1))
number2=$((($number2%$RANGE)+1))
echo number 1 is $number1
echo number 2 is $number2
# add 2 numbers
sum=$(($number1+$number2))
echo sum is $sum
#return the sum
return $sum
}
# play_game() function invoked whenever user wants to play
play_game(){
# first throw
generate_random_number
sum=$?
# check if win or lost
if(($sum==2 || $sum==3 || $sum==12))
then
# lost then subtract wager from total amount
amount=$(($amount-$wager))
echo You Lost $wager$
fi
答案1
答案2
注意,对于 shell 编程,该return
命令用于传达地位的函数,而不是价值。值通过 stdin 和 stdout 传递。这意味着调试/详细消息必须打印在 stderr 上:
roll_dice() {
local range=6
local sum=0
# add 2 random numbers
for i in {1..2}; do
(( sum += (RANDOM % range) + 1 ))
done
# "diagnostic" output to stderr
echo "sum is $sum" >&2
# values returned on stdout
echo "$sum"
}
然后你就做
play_game() {
# first throw
# capture the value using command substitution
sum=$( roll_dice )
如果您想放弃诊断输出:
sum=$( roll_dice 2>/dev/null )
笔记:
- 一致性是代码可读的关键:要么将左大括号放在新行上,要么放在同一行上,但不能两者都放在一起
- 不要使用全部大写的变量名:保留为 shell 保留的变量名
- 在 bash 算术表达式中,
$
变量不需要
答案3
由于这是bash
,因此您在脚本末尾遗漏了一些内容。
[...]
amount=$(($amount-$wager))
echo You Lost $wager$
fi
# close function
}
# get a wager
read -p "Enter wager " wager
# validate and call play_game()
((wager>0)) && play_game || echo "Invalid wager: $wager"
这是 TIO 上的: