Adding a zero to single digit variable
Solution 1
You can replace the whole lot with:
for day in 0{1..9} {10..31} ; do
mkdir ${path}/02.${day}.2011
done
while still not having to start up any external processes (other than what may be in the loop body).
That's probably not that important here since mkdir
is not one of those things you tend to do a lot of in a tight loop but it will be important if you write a lot of your quick and dirty code in bash
.
Process creation is expensive when you're doing it hundreds of thousands of times as some of my scripts have occasionally done :-)
Example so you can see it in action:
pax$ for day in 0{8..9} {10..11}; do echo ${day}; done
08
09
10
11
And, if you have a recent-enough version of bash
, it will honor your request for leading digits:
A sequence expression takes the form
{x..y[..incr]}
, wherex
andy
are either integers or single characters, andincr
, an optional increment, is an integer.When integers are supplied, the expression expands to each number between
x
andy
, inclusive.Supplied integers may be prefixed with
0
to force each term to have the same width. When eitherx
ory
begins with a zero, the shell attempts to force all generated terms to contain the same number of digits, zero-padding where necessary.
So, on my Debian 6 box, with bash
version 4.1.5:
pax$ for day in {08..11} ; do echo ${day} ; done
08
09
10
11
Solution 2
You can use
$(printf %02d $i)
To generate the numbers with the format you want.
for i in $(seq 0 1 31)
do
mkdir $path/02.$(printf %02d $i).2011
done
Solution 3
Better:
for i in $(seq -f %02g 1 31)
do
mkdir "$path/02.$i.2011"
done
Or even:
for i in {01..31}
do
mkdir "$path/02.$(printf "%02d" $i).2011"
done
Solution 4
In Bash 4, brace range expansions will give you leading zeros if you ask for them:
for i in {01..31}
without having to do anything else.
If you're using earlier versions of Bash (or 4, for that matter) there's no need to use an external utility such as seq
:
for i in {1..31}
or
for ((i=1; i<=31; i++))
with either of those:
mkdir "$path/02.$(printf '%02d' "$i").2011"
You can also do:
z='0'
mkdir "$path/02.${z: -${#i}}$i.2011"
Using paxdiablo's suggestion, you can make all the directories at once without a loop:
mkdir "$path"/02.{0{1..9},{10..31}}.2011
Solution 5
$ seq --version | head -1
seq (GNU coreutils) 8.21
$ seq -f "%02g" 1 10
01
02
03
04
05
06
07
08
09
10
Admin
Updated on August 11, 2020Comments
-
Admin almost 4 years
Trying to add a zero before the varaible if it's less than 10 and create said directory. I can't seem to get the zero to add correctly. Keeps resulting in making
02.1.2011
,02.2.2011
etc,etc.i=0 for i in {01..31} do if $i > 10 then mkdir $path/02.0$i.2011 else mkdir $path/02.$i.2011 fi done