I was here trying to solve the factorial of a number passed as an argument, and since I am one of those who do paranoid checking, I had thought it would be interesting to check that if the parameter entered is a letter, it gives an error because the number cannot be calculated factorial of a letter.
Well, I was browsing the forum and found a way to do it, the problem is that I don't know what's wrong with my code, since with the check moving it from lines it doesn't even calculate the factorial of the number, I get the error message that It should come out in case it was a letter, and modifying the parameters of the check, it always gives me an error in one of the parts.
Here is my code:
#!/bin/bash
# Factorial de un número pasado por parámetro:
clear
#Primero declaramos las variables inicializadas con un valor.
#Al igual que en C, en este caso inicalizamos en 1, ya que inicializarlas en 0, la multiplicación del factorial, sería siempre 0.
factorial=1
contador=1
if test "$1" = ""; then
echo "El script necesita de un número entero para ejecutarse. Intentelo de nuevo. "
sleep 2
echo "Saliendo del script... "
sleep 2
exit 1
else
validar_numero='^-?[0-9]+([.][0-9]+)?$'
if ! [[ "$1"=~"$validar_numero" ]]; then
echo "Lo que se ha introducido no es número entero positivo. "
exit 2
else
while [[ $1 -ge $contador ]]; do
factorial=`expr $factorial \* $contador`
contador=`expr $contador + 1`
done
fi
echo "El factorial de $1 es $factorial. "
fi
The way I run my script is:
chmod 777 factorial.sh
./factorial.sh