Bash Script

Karl Auer kauer at biplane.com.au
Tue Oct 24 13:11:09 UTC 2006


On Tue, 2006-10-24 at 13:38 +0100, Tony Arnold wrote:
> > Good call, but the code is still broken, because the problem was not
> > only with printf, but also with the expansion of $Num in "Num=$((Num
> > +1));"
> 
> Why is this broken in my version? $Num never gets leading zeros with my
> code, so far as I can see, although I no longer have the original, so I
> could be missing something.

Did you make your suggested change and run the script ten times? If you
did and nothing went wrong, then I can only assume your version of bash
and mine differ somehow. I cut-and-pasted OOzy's latest version into a
file, set the file to executable, and tried it:

- with no project files in the directory, it treats the file spec as a
list and issues scary messages when it tries to check "[0" as a number.
It goes ahead and creates 00-project anyway though.

- if not run in $WORKINGDIR it will not find the project files, leading
to the problem above and the problem that it will never be able to
create anything other than an 00-project :-) and that only the first
time - after that it will say that it can't, because the directory
already exists.

- trying to create the tenth project directory (09-project), the exact
symptoms OOzy described happened.

Then I applied your changes and tried again. The same symptoms on the
tenth loop! Why? Because 07 (octal) plus 1 is 8 (decimal). When $Num is
07, the addition (correctly) gives 8, but the next time around, that 8
comes from a directory prefix and looks like "08". It is *presented*
that way in the addition. The addition fails, seeing an invalid octal
number, so $Num still contains "08". That's what printf then sees, and
printf complains for the same reason.

$Num leads a double life - after the addition, it is a mild-mannered
decimal number with no leading zeros because the result of the addition
was assigned in decimal (i.e., as a string without leading zeros) to
$Num. But the directory name prefix is a string that may contain a
leading zero; when such a string is assigned to $Num the leading zero
doesn't get dropped and $Num ends up looking like an octal number. The
first time that happens is on the tenth loop.

The trick is therefore to make the string version of $Num look like a
decimal by stripping the leading zero.

Regards, K.

-- 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Karl Auer (kauer at biplane.com.au)                   +61-2-64957160 (h)
http://www.biplane.com.au/~kauer/                  +61-428-957160 (mob)





More information about the ubuntu-users mailing list