I need to give a value and be able to get the square, and this action must be repeated until the number is 99, I know it will be done with a loop, but I can't find a way to repeat it the way I want, already that of the forms that I have tried, it takes the square of the number that I have entered up to 99 at once, and I want it to do it one by one, until it is a number greater than 99, which in that case will give an error.
I leave you the code that I have so far, I hope you can help me:
#!/bin/bash
echo "Escribe un valor para sacar su cuadrado de 1 a 99"
read A
if [ $A -le 99 ]
then
cuadrado=`expr $A \* $A`
echo "El cuadrado de $A es $cuadrado"
else
echo "Error, el número es mayor que 99"
fi
Indeed, what you need is a loop , in this case it seems more convenient to use the
while
, although you canfor
also use a, since it is known that it should not be greater than 99.So I placed the
while
before conditionalif/else
, as follows:OPTIMIZED CODE
I was analyzing this code, and the way in which it is developed and I see that it is not efficient because if you put a number greater than 99 it does nothing because it does not enter the
while
, I also realized that the conditional inif/else
in this case is not doing nothing, I have optimized the code executing first theif/else
and then thewhile
, in this way it works well, it is interesting, because I did not change the code, I simply ordered it so that it was optimal.I hope to be helpful!
You don't need any loop to do what you ask (or what I understand you ask). It is not recommended to make loops with
bash
even though it may look very seductive. For that you can use other programs. You don't even need aelse
.What I suggest is to use
seq
to generate numbers from the input to the limit (which will be 99) and then usexargs
to output the result of seq and get the squares withbc
.Whose execution would be like this.
Another alternative without depending on external command could be: