My code:
#! /bin/bash
contador = 0
while :
do
echo -n "Escriba el nmero:"
read numero
case $numero in
(""|*[^0-9]*) printf "\nError: [numero] no es un caracter valido\n";;
(*) printf "\nEl primer digito es: ${numero:0:1}";;
esac
echo -n "Si quiere volver a intentarlo presione 1, de lo contrario presiona cualquier otra cosa"
read volver
if [[ $volver != 1 ]]
then
echo "El nmero de vces usado fue $contador"
echo "Adios"
sleep 2
break
fi
contador = contador + 1
done
When I run it, it tells me:
line 26: counter: not found.
I thought it was 0 by default and that's why at first I did it without defining the counter outside of the while. Since it didn't help, I defined it outside but nothing, the same thing continues, the counter had it up and I passed it to the end of the while but nothing, the same.
Thanks in advance.
The assignment cannot have spaces around the equals, that is, line 2 must be:
And on the other hand, the line in which you try to increment the counter has several problems. On one side, again the spaces around the equal. On the other hand, on the right you should use
$contador
instead ofcontador
to get the value it had, but finally, most important of all, the shell language is not a programming language, but a command execution language, and it tends to consider the variable values as strings instead of numbers. The line:it will not produce the expected result, but, for example, if the loop is executed three times, in the end it
$contador
will be valued0+1+1
(as a string).For mathematical calculations you must use
let
with a syntax like the following:Notice that
let
you pass a string to it (all in quotes), but the$contador
will be expanded to its value inside the quotes, so itlet
will see something likecontador = 0 + 1
the first iteration, and it will mathematically evaluate the expression, which will return it1
, and will assign tocontador
. When you uselet
, by enclosing the expression in quotes, you can use spaces more freely.