bashfor-loop

Writing a shell script to loop and print out numbers 0-100 and if they are even or odd


I'm trying to write a script to do as the question title says but I'm getting an error and I can not understand why. I'm quite new to bash and shell scripting so any help is appreciated. here is my code:

for i in {0..100}
do
if [ $i % 2 = 0  ]
        echo "Number: $i and is even."
else
        echo "Number: $i and is odd."
fi
done

Solution

  • You are missing a then after if. Also your test expression in if is incorrect

    for i in {0..100}
    do
    if [ $(($i % 2)) -eq 0  ]
    then
            echo "Number: $i and is even."
    else
            echo "Number: $i and is odd."
    fi
    done
    

    $(($i % 2)) is for Arithmetic-Expansion