user2045447
user2045447

Reputation: 1411

How to print an integer zero-filled to a.given width?

I am doing something like this with bash

number=1
while [ $number -le 10 ]; do
    echo $number
    number=$((number+1))
done

This will output:

1
2
3
4
5
6
7
8
9
10

.

What can I do if I want the total digits of the integer as, e.g., two. If the integer has fewer digits than two, then fill with zero on the left. In other words, I want output like this:

01
02
03
04
05
06
07
08
09
10

Is there someone knowing how to manage this? Thanks:)

Upvotes: 2

Views: 238

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191729

Use printf instead of echo:

printf "%02d\n" $number

Upvotes: 3

Related Questions