Continuing from my comment, the simplest way to create sequential 5-digit directory names, creating the next available directory on each run of your script is to form the number using printf -v var ...
Example, to create a 5-digit number storing the result in var
you use printf -v var "%05d" "$count"
. If count contained 4
that would store 00004
in var
.
To determine which is the next available directory, loop starting at 1
with while [ -d "parent/$var" ]
and increment the number in var
each time until you find a number in var
for which the parent/$var
directory doesn't exist and then simply create the new directory. You can set a default value for parent
of .
(present working directory) or take the parent path as your first argument. (you can take the number to start counting at as your 2nd argument with a default of 1
)
Putting it altogether, you could do:
#!/bin/bash
parent="${1:-.}" ## parent directory as 1st arg (default .)
count="${2:-1}" ## initial count as 2nd arg (default 1)
printf -v dname "%05d" "$count" ## store 5 digit number in dname
while [ -d "$parent/$dname" ] ## while dir exists
do
((count++)) ## increment count
printf -v dname "%05d" "$count" ## store new 5 digit number in dname
done
printf "creating %s\n" "$parent/$dname" ## (optional) output dirname
mkdir -p "$parent/$dname" ## create dir
Example Use/Output
With the script in createseqdir.sh
and the parent directory location as dat
, e.g.
$ l dat
total 24
drwxr-xr-x 5 david david 4096 Nov 28 20:16 .
drwxr-xr-x 3 david david 4096 Nov 28 20:16 ..
drwxr-xr-x 2 david david 4096 Nov 28 20:12 00001
drwxr-xr-x 2 david david 4096 Nov 28 20:12 00002
drwxr-xr-x 2 david david 4096 Nov 28 20:12 00003
You could do:
$ bash createseqdir.sh dat
creating dat/00004
Resulting in:
$ l dat
total 28
drwxr-xr-x 6 david david 4096 Nov 28 20:30 .
drwxr-xr-x 3 david david 4096 Nov 28 20:29 ..
drwxr-xr-x 2 david david 4096 Nov 28 20:12 00001
drwxr-xr-x 2 david david 4096 Nov 28 20:12 00002
drwxr-xr-x 2 david david 4096 Nov 28 20:12 00003
drwxr-xr-x 2 david david 4096 Nov 28 20:30 00004