Bash create directory with sequential numbers

I am creating a script to run on OS X that will be run by a often novice user and therefore wants to protect the directory structure by creating a new one each time with n + 1 for the last:

target001 with the following run creating target002

I still:

 lastDir=$(find /tmp/target* | tail -1 | cut -c 6-) let n=$n+1 mkdir "$lastDir""$n" 

However, math does not work here.

0
source share
5 answers

No pipes and subprocesses:

 targets=( /tmp/target* ) # all dirs in an array lastdir=${targets[@]: (-1):1} # select filename from last array element lastdir=${lastdir##*/} # remove path lastnumber=${lastdir/target/} # remove 'target' lastnumber=00$(( 10#$lastnumber + 1 )) # increment number (base 10), add leading zeros mkdir /tmp/target${lastnumber: -3} # make dir; last 3 chars from lastnumber 

Version with two parameters:

 path='/tmp/x/y/z' # path without last part basename='target' # last part targets=( $path/${basename}* ) # all dirs in an array lastdir=${targets[@]: (-1):1} # select path from last entry lastdir=${lastdir##*/} # select filename lastnumber=${lastdir/$basename/} # remove 'target' lastnumber=00$(( 10#$lastnumber + 1 )) # increment number (base 10), add leading zeros mkdir $path/$basename${lastnumber: -3} # make dir; last 3 chars from lastnumber 
+1
source

What about mktemp ?

  Create a temporary file or directory, safely, and print its name.
 TEMPLATE must contain at least 3 consecutive `X in last component.
 If TEMPLATE is not specified, use tmp.XXXXXXXXXX, and --tmpdir is
 implied.  Files are created u + rw, and directories u + rwx, minus umask
 restrictions.
+2
source

Use this line to calculate the new serial number:

 ... n=$(printf "%03d" $(( 10#$n + 1 )) ) mkdir "$lastDir""$n" 

10 # to force base 10 arithmetic . Provided that $ n remains the last. "001".

+2
source

Complete solution using the advanced test [[and BASH_REMATCH:

 [[ $(find /tmp/target* | tail -1) =~ ^(.*)([0-9]{3})$ ]] mkdir $(printf "${BASH_REMATCH[1]}%03d" $(( 10#${BASH_REMATCH[2]} + 1 )) ) 

Provided by / tmp / target001 is the template for your directory.

+1
source

Like this:

 lastDir=$(find /tmp/target* | tail -1) let n=1+${lastDir##/tmp/target} mkdir /tmp/target$(printf "%03d" $n) 
0
source

All Articles