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

64 Views Asked by At

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.

2

There are 2 best solutions below

2
Ted Lyngmo On BEST ANSWER

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"
1
Ajay On

The script you've provided has a few issues that need to be corrected to make it work properly. Here's my version of the script:

#!/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"

Here's what I fixed:

Inside the if statement, you should have a space after [ and before ], and also a space around the $((i % 2)) expression. So it should be [ $((i % 2)) -eq 0 ] instead of [[$(($i%2)) -eq 0]].

With these changes, the script should correctly count and display the number of even (pares) and odd (impares) numbers between 1 and the input number n.