2 statements in for loop

Bash shell, variables i and rem are working fine in 2 separate for loops, but I'd like to consolidate them like this:

for  [ i in $((x*x)) ]  && [ rem in $((((i % 2)) | bc)) ] 

This gives syntax error on && .
Thanks in advance for direction.

I'd be surprised if the error occurs when && is encountered, as none of the two bash for - loop syntaxes are met.

What exactly are you after?

Thanks for reply. Here is the working script. You can see commented section referenced in first post; I'd like to consolidate:

#!/bin/sh

x=0

echo 'Enter number:'
read x
for  i in $((x*x))  #&& [ rem in $((((i % 2)) | bc)) ] 
do
echo "Square of $x is $i."
done

for rem in $((((i % 2)) | bc))
do
if [ $((i % 2)) -eq 0 ]; then
    echo "$i is even, because the remainder of $i divided by 2 is 0."
else
    echo "$i is odd, because the remainder of $i divided by 2 is $rem, not 0."

fi
done 

The for construct is used to iterate through a list or repeatedly evaluate an expression. Using it for one single value is at least, hmmm, questionable, as the loop variable is set to exactly that single value.

x=0
echo 'Enter number:'
read x
i=$((x*x))  #&& [ rem in $((((i % 2)) | bc)) ]   # integer arithmetics.
echo "Square of $x is $i."
rem=$((i % 2))                                   # bash can do integer arithmetics only, so NO bc needed...
if [ $rem -eq 0 ]
  then echo "$i is even, because the remainder of $i divided by 2 is 0."
  else echo "$i is odd, because the remainder of $i divided by 2 is $rem, not 0."
fi
1 Like

Hello p1ne,
I would like to help you to make good scripts. But to do this I want you to think about the following questions:

  1. what is the use of "for loops"? Why would one use them?
  2. to how many values will $((x*x)) be evaluated?
  3. would the chosen construction be the best way to reach your goal?

Thanks again RudiC, I understand now that loop is questionable for single value.

x=0
echo 'Enter number:'
read x
i=$((x*x))  #&& [ rem in $((((i % 2)) | bc)) ]   # integer arithmetics.
echo "Square of $x is $i."
rem=$((i % 2))                                   # bash can do integer arithmetics only, so NO bc needed...
if [ $rem -eq 0 ]
  then echo "$i is even, because the remainder of $i divided by 2 is 0."
  else echo "$i is odd, because the remainder of $i divided by 2 is $rem, not 0."
fi