Make directory named 0001 instead of 1 in a bash script loop
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.)
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