skelator
skelator

Reputation: 23

Increment a zero padded int in Bash loop

I'm trying to automate files rename/creation, I have a initial script for testing, I have already looked around I can't find anything related

here is my sample script

#!/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

script work fine when the initial files is not present/exist but start goes wrong after the 3 occurrence as in the sh -x below

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
$

after 001 it fallback to -2 without leading zeros,any input on what I did wrong is much appreciated
Thanks

Upvotes: 0

Views: 1421

Answers (1)

chw21
chw21

Reputation: 8140

Your problem seems to be that 001++ turns into 2 and not 002. Why not use

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

Less lines, but also more confusing:

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

Update: Use the printf -v padded_i suggestion from the comments

Upvotes: 1

Related Questions