我正在尝试编写一个输入数字的脚本,然后输入另一个值,如果该值与输入的第一个数字相同,则会添加到cnt变量,然后让您输入另一个数字进行检查。应该重复此操作,直到两个数字不匹配,然后打印值发生的次数。我遇到循环问题,输入第二个值后,它会连续打印: 5次出现
#!/bin/bash
read currVal
if [ -n $currVal ]; then
cnt=1
read val
while [[ -n $val ]]
do
if [[ $val == $currVal ]]; then
cnt=$((cnt+1))
else
echo "$currVal occurs $cnt times"
fi
done
fi
答案 0 :(得分:1)
正如@anubhava建议的那样,这种修改对我有用:
#!/bin/bash
read currVal
cnt=1
val=$currVal
while [[ -n $val ]]
do
echo enter next
read val
if [[ $val == $currVal ]]; then
cnt=$((cnt+1))
else
echo "$currVal occurs $cnt times"
exit
fi
done
答案 1 :(得分:0)
计算输入值的变量:
declare -A counts
while :
do
read -r -p 'Enter number (or press enter to finish) > ' num
[[ -z "$num" ]] && break
((counts["$num"]++))
done
for key in "${!counts[@]}"
do
printf "entered %s: %s times\n" "$key" ${counts["$key"]}
done | sort -n