Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In the following bash script if j=0000 how have I to change the following bash script to make dirs named 0001, 0002, ...? Actually it make dirs named 1, 2, 3

for i in *.jpg; do let j+=1 ; mkdir $j ; done


share|improve this question

Your current script uses only a decimal value - this obviously translates to the value without leading zeroes.

You would have to pad the string to the length of 4 characters, with leading zeroes. You do this by using backticks `` to get the result of the printf call printf %04d $j.

As a result, you should have the full command:

for i in *.jpg; do let j+=1; mkdir `printf %04d $j`; done

Source: StackOverflow: bash - Padding zeros in a string

(Obviously also see the further answers to that question, if you want a more in-depth solution, but this definitely works perfectly for this use case.)

share|improve this answer

Using bash, your best option is:

mkdir {0001..0666}

to create dirs with name 0001 to 0666 (with zero padding).

If you want directories named prefix0001suffix, prefix0002suffix, ... then:

mkdir prefix{0001..0666}suffix

will do.

If you only want odd number directory names

mkdir {0001..0666..2}

and so on... See Brace Expansion in the bash reference manual.

As FEichinger points out, you need to know in advance the number of directories. If you want a solution that is close to yours, but really safe and using more modern bash idiom:

for i in *.jpg; do ((++j)); mkdir $(printf "%04d" $j) ; done
share|improve this answer
This is only useful for a previously known amount of directories to be created. Usually, when using numbered directories, you are within a dynamic context - which means it should determine the amount at runtime and thus still needs string padding. Depends on the specific use case, though. – user98085 Dec 19 '12 at 18:30
@FEichinger Right! post edited accordingly. – gniourf_gniourf Dec 19 '12 at 18:39

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.