最后编辑:使正则表达式更精确并更正一些计数错误。
就像是:
create_folder() {
if [ -e "$1" ] ;then
counter=1;
while [ -e "$1-$counter" ] ;do
counter=$((counter+1))
done
mkdir "$1-$counter";
else
mkdir "$1";
fi;
}
能做:
$ ls -ltr /tmp |grep foo
$ create_folder /tmp/foo\ bar
$ create_folder /tmp/foo\ bar
$ create_folder /tmp/foo\ bar
$ ls -ltr /tmp |grep foo
drwxr-xr-x 2 user user 4096 1 mai 10:53 foo bar
drwxr-xr-x 2 user user 4096 1 mai 10:53 foo bar-1
drwxr-xr-x 2 user user 4096 1 mai 10:53 foo bar-2
或使用更好的格式和另一种计数方式(如果存在许多目录则更快,因为它使用专门的计数功能,但如果因为分叉而更长。):
create_folder() {
if [ -e "$1" ] ;then
counter=`/bin/ls -1 "$1" "$1-"* 2>&1 | grep -E "^$1(-[0-9]*)?" | wc -l`;
nname="`printf "%s-%04d" "$1" $counter`";
mkdir "$nname";
else
mkdir "$1";
fi;
}
这是在不同的shell实现下测试的:bash、dash、ash和ksh
$ create_folder /tmp/test
$ ls -ltr /tmp/| grep test
drwxr-xr-x 2 user user 4096 Apr 30 13:25 test
$ create_folder /tmp/test
$ create_folder /tmp/test
$ ls -ltr /tmp/| grep test
drwxr-xr-x 2 user user 4096 Apr 30 13:25 test
drwxr-xr-x 2 user user 4096 Apr 30 13:26 test-0001
drwxr-xr-x 2 user user 4096 Apr 30 13:26 test-0002
并且 dirname 包含空格:
$ create_folder "foo bar"
$ create_folder "foo bar"
$ create_folder "foo bar"
$ create_folder "foo bar"
$ ls -ltr | grep foo
drwxr-xr-x 2 user user 4096 Apr 30 13:35 foo bar
drwxr-xr-x 2 user user 4096 Apr 30 13:35 foo bar-0001
drwxr-xr-x 2 user user 4096 Apr 30 13:35 foo bar-0002
drwxr-xr-x 2 user user 4096 Apr 30 13:35 foo bar-0003
create_folder() {
local -a list
local counter nname
if [ -e "$1" ] ;then
list=("$1-"*)
list=(${list[@]// /_})
list=(${list[@]//*\*})
counter=$((${#list[@]}+1))
printf -v nname "%s-%04d" "$1" $counter
mkdir "$nname";
else
mkdir "$1";
fi;
}
非常快,没有分叉和漂亮的格式:
$ create_folder "/tmp/foo bar"
$ create_folder "/tmp/foo bar"
$ create_folder "/tmp/foo bar"
$ create_folder "/tmp/foo bar"
$ ls -ltr /tmp/ | tail -n 4
drwxr-xr-x 2 user user 4096 1 mai 11:17 foo bar
drwxr-xr-x 2 user user 4096 1 mai 11:17 foo bar-0001
drwxr-xr-x 2 user user 4096 1 mai 11:17 foo bar-0002
drwxr-xr-x 2 user user 4096 1 mai 11:17 foo bar-0003