Bash Script

Karl Auer kauer at biplane.com.au
Tue Oct 24 12:26:14 UTC 2006


On Tue, 2006-10-24 at 12:10 +0100, Tony Arnold wrote:
> The problem is that $NUM has the leading zeros, so when it gets
> substituted in the printf line, bash thinks it is an octal number,
> because numbers starting with a zero are considered octal. By keeping
> $NUM as just the number, you avoid this.

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));"

A solution that works is to add, immediately after the first assignment
to Num, the line "Num=${Num##0}", which will strip any leading zero,
making $Num an ordinary decimal number instead of octal.

I think the script as given has two other problems though - it should be
working in $WORKINGDIR, and it will issue error messages if there are no
numbered projects the first time it runs.

Here is my working version:

#!/bin/bash

PROJECT=$1
WORKINGDIR="/path/to/working/dir"
cd $WORKINGDIR

# Test for existence of zeroth project
if [ ! -e 00-* ] ; then
   Num=0
else
   MaxIndex=0
   for dir in [0-9][0-9]-* ;
   do
      Num=${dir%%-*}
      Num=${Num##0}
      if [ $MaxIndex -lt $Num ]; then
         MaxIndex=$Num
      fi
   done
   Num=$((Num+1));
fi

Num=$(printf %02d $Num)
PROJECT=$Num-$PROJECT

mkdir $PROJECT

exit

-- 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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