bash script issue

Walter Dnes waltdnes-SLHPyeZ9y/tg9hUCZPvPmw at public.gmane.org
Wed Sep 3 22:55:43 UTC 2014


On Wed, Sep 03, 2014 at 03:19:49PM +0000, Peter wrote
> D. Hugh Redelmeier <hugh at ...> writes:
> 
> > I don't remember an ordinary shell context where a pathname can be
> > confused with number.  Can you give an example?
> 
> Ordinary not, but:
> 
> echo $((07+1)) -> 8 (yes... why?)
> echo $((007+1)) -> 8 (hmm, must be Mr. Bond)
> echo $((077+1)) -> 64 (no kidding, 077oct is 64dec)
> echo $((078+1)) -> bash: 078: value too great for base (error token is "078")
> 
> So if you do any math on any numbers for example numbered files like
> DCIM/IMG0077.jpg you WILL likely be bitten. I think the 1st application
> where I was bitten was many years ago trying to figure out missing and
> duplicate IMGnnnnn.jpg files in a large recovered image directory. I also
> tried to be clever and rename files such that there would be no gaps upon
> finding missing files, in one pass. That did not go well, I had a 10% or so
> file loss when done. There are many other 'opportunities' to get bitten.

  I use bash in many cases where other people would use "R" or whatever.
Leading zeros in numbers come up so often, I've written my own function
to handle the situation.  You can include it at the top of a program
like so...

#!/bin/bash
#
# bash treats leading zeros as indicating octal, freaks out on 08 or 09,
# and numbers 010 and above are just plain wrong.  So strip leading zeros.
strip_leading_0() {
   stripped="${1}"
# 
# Leave plain "0" alone.  Only strip zeros if string is longer
# than one character.
   while [ ${#stripped} -gt 1 ] && [ "${stripped:0:1}" == "0" ]
   do
      stripped=${stripped:1}
   done
   export stripped
}
...
#
# "Sanitize" numeric variable foobar
strip_leading_0 ${foobar}
foobar=${stripped}

...or you can set up and load a common function library as shown at
http://bash.cyberciti.biz/guide/Shell_functions_library

-- 
Walter Dnes <waltdnes-SLHPyeZ9y/tg9hUCZPvPmw at public.gmane.org>
I don't run "desktop environments"; I run useful applications
--
The Toronto Linux Users Group.      Meetings: http://gtalug.org/
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://gtalug.org/wiki/Mailing_lists





More information about the Legacy mailing list