Asnim P Ansari
Asnim P Ansari

Reputation: 2477

How to increment numbers in bash script?

I am trying to print odd numbers from 1 - 99, using the script below.

start=1
while [[ $start -le 100 ]]
do 
    echo $start
    start=start+2

done

but instead of getting numbers my output looks like

1
1+2
1+2+2
1+2+2+2
1+2+2+2+2
1+2+2+2+2+2
1+2+2+2+2+2+2
1+2+2+2+2+2+2+2

What did I miss here?

Upvotes: 2

Views: 4905

Answers (4)

Hello try something like this:

for (( NUM=1; NUM<=100; NUM=NUM+2 )); do
    echo $NUM
done

Upvotes: 1

Benjamin W.
Benjamin W.

Reputation: 52112

As pointed out, your problem is that you're not increasing the number properly, you have to use something like

start=$((start + 2))

or

((start += 2))

However, you can avoid the whole loop:

printf '%d\n' {1..100..2}

Upvotes: 1

Carlos
Carlos

Reputation: 376

You have to use Aritmetic Expansion:

Arithmetic expansion provides a powerful tool for performing (integer) arithmetic operations in scripts.

Example:

start=$((start + 2))

The cleanest code I can do to print odd numbers is:

start=1
while [[ $start -le 100 ]]
do
    echo $((start += 2))
done

Upvotes: 6

Shmuel
Shmuel

Reputation: 1668

Jest wrap the start+2 like below

start=$((start+2))

Here is some more details

The link is from This Answer

Upvotes: 1

Related Questions