'Bash script to give n numbers and print even numbers

I'm trying to write a bash script for

"Given a positive integer N greater than 1, make a script to show the even numbers between 0 and N. Ex .: The number 12 has been read. The program must have as output: 0, 2, 4, 6, 8, 10 and 12;"

So far I did like this:

ex5.sh

#!/bin/bash

echo "Number :"
read num;

for (( i = 1; i >= $num; i++ ))
do
   if [ $(($i % 2)) -eq 0 ]
   then
        echo $i
   fi
done

When i compile, it doesn't print numbers. I couldn't find where is the problem

I tried using for-in loop as well

#!/bin/bash

echo "Number :"
read num;

for i in $num
do
   if [ $(($i % 2)) -eq 0 ]
   then
        echo $i
   fi
done

This time only print the number that i put as a input. For example, I put 4 in terminal it prints 4 as well

Many thanks



Solution 1:[1]

This way can make your code working:

echo -n "Number : "
read num;

for i in $(seq 0 $num)
do
   if [ $(expr $i % 2) == 0 ]
   then
        echo $i
   fi
done

bash ex5.sh
Number : 12
0
2
4
6
8
10
12

Solution 2:[2]

` echo -n "Number : " read num;

for i in $(seq 0 $num) do if [ $((num%2)) -eq 0 ] then echo $i fi done `

Solution 3:[3]

#!/bin/bash

read -p "Number: " num
awk '{for(i=0;i<=$1;i++) if(i%2 == 0) print i}'<<<$num

./printNumbers.sh
Number: 8
0
2
4
6
8

# to get a list use printf
awk '{for(i=0;i<=$1;i++) if(i%2 == 0) printf i","}'<<<$num | sed 's/,$//'

./printNumbers.sh
Number: 8
0,2,4,6,8

Solution 4:[4]

#!/usr/bin/env bash
read -p 'Number: ' num
seq 0 2 "$num"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Idan Zohar
Solution 3
Solution 4 Ed Morton