3

I'm trying to make a list with a simple bash looping

I want this:

000000 000001 000002 

They give me this:

0 1 2 

My shell code:

countBEG="000000" countEND="999999" while [ $countBEG != $countEND ] do echo "$countBEG" countBEG=$[$countBEG +1] done 
4
  • 1
    The problem is that when you use arithmetic operations, leading zeroes are meaningless and thus stripped. You might want to work on numbers from the beginning, then pad them when you display them (with printf for example) Commented Oct 17, 2017 at 14:44
  • As an alternative echo {000..009} or seq -f '%05g' 0 9 Commented Oct 17, 2017 at 14:52
  • 2
    Numbers aren't zero-padded; string representations of them are, and $((...)) (don't use $[...], it's long been deprecated) simply returns the simplest representation it can for its expression. Commented Oct 17, 2017 at 15:36
  • 1
    @Aaron, pedantically, leading zeroes are highly significant for arithmetic operations: they denote octal numbers: x="08"; ((x++)) Commented Oct 17, 2017 at 16:41

3 Answers 3

3

Change your echo to use printf, where you can specify format for left padding.

printf "%06d\n" "$countBEG" 

This sets 6 as fixed length of the output, using zeros to fill empty spaces.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @123 for fixing the broken formatting. Was trying to figure out how to escape backticks :)
4 space at the start of the line for a code-block, all other formatting is then ignored :)
2

The following command will produce the desired output (no need for the loop) :

printf '%06d\n' {1..999999} 

Explanation :

  • {1..999999} is expanded by bash to the sequence of 1 to 999999
  • the format string '%06d\n' tells printf to display the number it is given as argument padded to 6 digits and followed by a linefeed
  • printf repeats this output if it is given more arguments than is defined in its format specification

9 Comments

why would you use g ?
Just a small change, OP needs 6 digits I think.
g will change larger number to scientific notation, not the zero padded string op wants
@123 thanks for the explanation, I've changed it to d
Starting in bash 4.0, brace expansion will preserve leading zeros, eliminating the need for printf: {001..100} produces 001 002 003 ... 100.
|
2

You're looking for:

seq -w "$countBEG" "$countEND" 

The -w option does the padding.

4 Comments

That's it. Thank you brow.
@anubhava, done. How many undelete votes are required to re-open?
Thanks so much. It will need 1 more undelete vote. Please also vote to reopen.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.