我想要一个bash脚本来创建名为“exam_folder”的文件夹,如果这个文件夹已经存在(例如我再次运行脚本),脚本会创建“exam_folder_1”并且该文件夹是否存在我希望脚本创建“exam_folder_2”,依此类推。我想聪明地拥有它:) 我有这样的事情:
function create_folder {
if [ -d "$1" ]; then # if exists
mkdir $1_`i_max` # function i_max would find out the max number and add 1
else
mkdir $1
fi }
感谢您的帮助。
答案 0 :(得分:0)
上次修改 让regexp更加精确并纠正一些计数错误。
类似的东西:
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
答案 1 :(得分:0)
这应该适用于任何符合POSIX标准的shell(尽管我对[ "$foo" -eq "$foo" ]
is-number-check不是100%肯定)。我在dash
和busybox' ash
下进行了快速测试。
create_folder()
{
if [ -e "$1" ]; then
i=0
for d in "$1"_*; do
_i="${d##*_}"
[ "${_i}" -eq "${_i}" ] 2>/dev/null && i="${_i}"
done
i=$((i+1))
mkdir "$1_${i}"
else
mkdir "$1"
fi
}
答案 2 :(得分:0)
你可以这样做:
max=`ls -1d exam_folder* | tr -dc '[0-9\n]' | sort -k 1,1n | tail -1`
mkdir exam_folder_$((max + 1))
请注意,如果您对此有所了解,它将不会填充序列中的“漏洞”。