0

我正在尝试自动化文件重命名/创建,我有一个用于测试的初始脚本,我已经环顾四周我找不到任何相关的东西

这是我的示例脚本

#!/bin/bash
file=`hostname`
if [[ -e $file.dx ]] ; then
    i="$(printf "%03d" 1)"
    while [[ -e $name-$i.dx ]] ; do
        let i++
    done
    name=$name-$i
fi
touch $name.dx

当初始文件不存在/不存在但在第 3 次出现后开始出错时脚本工作正常,如下面的 sh -x

linux@cygwinhost ~/junkyard
$ sh -x exp.sh
++ hostname
+ name=cygwinhost
+ [[ -e cygwinhost.ext ]]
+ touch cygwinhost.ext

linux@cygwinhost ~/junkyard
$ sh -x exp.sh
++ hostname
+ name=cygwinhost
+ [[ -e cygwinhost.ext ]]
++ printf %03d 1
+ i=001
+ [[ -e cygwinhost-001.ext ]]
+ name=cygwinhost-001
+ touch cygwinhost-001.ext

linux@cygwinhost ~/junkyard
$ sh -x exp.sh
++ hostname
+ name=cygwinhost
+ [[ -e cygwinhost.ext ]]
++ printf %03d 1
+ i=001
+ [[ -e cygwinhost-001.ext ]]
+ let i++
+ [[ -e cygwinhost-2.ext ]]
+ name=cygwinhost-2
+ touch cygwinhost-2.ext

linux@cygwinhost ~/junkyard
$

在 001 之后它回退到 -2 而没有前导零,非常感谢任何关于我做错的输入
谢谢

4

1 回答 1

1

你的问题似乎是001++变成2而不是002。为什么不使用

i=1
printf -v padded_i "%03d" $i
while [[ -e ${name}-${padded_i}.dx ]] ; do
    let i++
    printf -v padded_i "%03d" $i
done

行数更少,但也更混乱:

i=1
while [[ -e ${name}-`printf "%03d" $i`.dx ]] ; do
    let i++
done
name=${name}-`printf "%03d" $i`.dx

更新:使用printf -v padded_i评论中的建议

于 2015-06-30T05:28:11.477 回答