[Gllug] Arithmetic error in bash on 08 and 09?

C. Cooke ccooke-gllug at gkhs.net
Thu Jul 22 13:02:14 UTC 2004


On Thu, Jul 22, 2004 at 12:19:44PM +0100, Holger Duerer wrote:
> >>>>> "Wulf" == Wulf Forrester-Barker <wulf.f-b at uhl.nhs.uk> writes:
>   [...]
> 
>     Wulf> Out of interest, is there a neater way this could be done in
>     Wulf> a bash script?
> 
> Hmmm.  What if you just remove the leading 0 before doing the
> arithmetic?
> 
> Something along the lines of (more general than necessary):
> 
> ,----
> | # Get the number
> | num=$(date +%U)
> | 
> | # Remove leading 0s (but not the last one remaining)
> | while [ $(expr $num : '0[0-9]') != 0 ]; do 
> |   num=$(expr substr $num 2 1000)
> | done
> | 
> | # Increment
> | num=$(expr $num + 1)
> | 
> | # Make it a file name:
> | Xfile=$(printf XXX%02d.log $num)
> `----
> 
> Wrap it in a function and your code will still be tidy...
> 
>         Holger

Or a little simpler and faster:

# Turn on extended globbing ( off by default in bash! )
shopt -s extglob

# Get the number
num="$(date +%U)"

# Strip off leading 0s (uses extended globbing)
clean="${num##+(0)}"
# preserve leading 0
stripped="${num%$clean}"

# Increment
(( clean++ ))

# Make it a file name:
Xfile="XXX${stripped}${clean}.log"

(The shell is actually very powerful, if you find out what it can do.
But remember to quote everything...)

-- 
Charles Cooke, Sysadmin
Say it with flowers, send a triffid.
-- 
Gllug mailing list  -  Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug




More information about the GLLUG mailing list