Search code examples
linuxbashscriptingspanish

How is the correct form to write a "if" conditional?


I want to know what is my mistake in this Bash scripting. It enters the for loop but when entering the if condition it only chooses the else option. The exercise is to count the even and the odd and I am using the Termux application:

#!/bin/bash
echo "Ingrese un numero"
read n
impar=0
par=0
for ((i=1; i<=$n ; i++));
do
 if [[$(($i%2)) -eq  0]];
 then
  ((par++))
 else
  ((impar++))
 fi
done
echo "Pares: $par"
echo "Impares: $impar"

I try to investigate but the information about if is different from one another. Please help me with that.


Solution

  • You need space after [[ but you could also use arithmetic expansion in the if statement too. Note that you don't need $ before your variables in arithmetic expansion:

    #!/bin/bash
    
    read -rp "Ingrese un numero: " n
    
    for (( i=1; i<=n; i++ )); do
        if (( i % 2 )); then
            ((impar++))
        else
            ((par++))
        fi
    done
    
    echo "Pares: $par"
    echo "Impares: $impar"
    

    A simpler version of your script could calculate the result without loops. You know there's at least the same amount of impars as there are pars - and there are n / 2 pars (with integer truncation). If you've given an uneven number as input, impar is equal to par + 1 or simply impar = n - par.

    #!/bin/bash
    
    read -rp "Ingrese un numero: " n
    
    (( par = n / 2 ))
    (( impar = n - par ))
    
    echo "Pares: $par"
    echo "Impares: $impar"