Reputation: 87
I am trying to write a script where you enter a number, then enter another value, if that value is the same as the first number entered, it adds to the cnt variable, then lets you input another number to check. It is supposed to repeated this until the two numbers do not match, and then print how many times the value occurred. I'm having trouble with the loop, after the second value is entered, it prints continuously: 5 occurs 1 times
#!/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
Upvotes: 0
Views: 246
Reputation: 63972
A variation what counts the entered values:
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
Upvotes: 0
Reputation: 283
As @anubhava suggests, this modification works for me:
#!/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
Upvotes: 1