bash使用序列号创建目录

时间:2013-04-26 02:57:14

标签: macos bash mkdir

我正在创建一个在OS X上运行的脚本,该脚本将由新手用户经常运行,因此希望通过每次创建一个新的目录结构来保护目录结构,最后使用n + 1:

target001下一次创建target002

我到目前为止:

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

然而,数学在这里不起作用。

5 个答案:

答案 0 :(得分:2)

怎么样? mktemp

Create  a  temporary  file  or directory, safely, and print its name.
TEMPLATE must contain at least 3 consecutive `X's 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.

答案 1 :(得分:2)

使用此行计算新序列号:

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

10#强制基地10 arithmetic。已经提供了$ n最后的保证金,例如“001”。

答案 2 :(得分:1)

没有管道和子流程:

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

包含2个参数的版本:

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

答案 3 :(得分:1)

使用扩展测试的完整解决方案[[和BASH_REMATCH:

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

提供/ tmp / target001是您的目录模式。

答案 4 :(得分:0)

像这样:

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