1

I need to use a for loop with 2-digit variables to define start and end values of the loop, for example: lstart=00 and lend=99. This will be used to print a sequence of 100 numbers for a number string like "56784XX" where the XX in the end will be starting from the lstart value, i.e. 00, and will be ending at the lend value, i.e. 99. So, output should be like:

5678400
5678401
5678402
5678403
.
.
.
.
5678499

The for loop like this:

for (( i = $lstart; i <= $lend; i++ )); do echo "56784${i}"; done

will display the first 10 values like:

567841
567842
567843
.
.
.
567849

i.e. missing the 0 digit, which is something that I do not wish. Also, this does not work:

for i in {$lstart..$lend}; do echo "56784${i}"; done

Can you please help with my requirement??

Thank you.

Kostas75
  • 331
  • 1
  • 4
  • 13

1 Answers1

3

use printf instead of echo:

for i in 1 2 3; do
    printf "56784%02d\n" $i
done

gives:

5678401
5678402
5678403

NOTE: while echo terminates by default with a newline \n, printf does not, so you have to specify it yourself.

Chris Maes
  • 35,025
  • 12
  • 111
  • 136
  • Good idea, however $lstart and $lend could be, respectively, 000, 999, or 0, 9, or 0000, 9999, etc., so this %02 is not constant at the printf, could need to be %03, or %01, or %04, etc. – Kostas75 Dec 10 '19 at 16:30