bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: leading zeros ignored by perl, ksh. not bash


From: Greg Wooledge
Subject: Re: leading zeros ignored by perl, ksh. not bash
Date: Wed, 23 Jul 2014 11:43:26 -0400
User-agent: Mutt/1.4.2.3i

On Wed, Jul 23, 2014 at 07:20:01AM +0000, address@hidden wrote:
> how we can declare hrs and min?
> or can we disable the automatic change from decimal to octal?

Strip the leading zeroes, or force base 10 with 10#$foo inside the math
context.

> TIME="08:09"

Using all-caps variables is going to bite you in the ass one of these
days.  The shorter and more common the variable name, the more likely
it will cause grief.  All-caps variable names are generally reserved
for environment variables (HOME, PATH), or shell variables that alter
the shell's behavior or reveal internal state (CDPATH, RANDOM).

> hrs=$(echo ${TIME}|cut -f1 -d ':')
> min=$(echo ${TIME}|cut -f2 -d ':')

Here's a variant that strips the leading zero.  This is my personal pick:

time="08:09"
hrs=${time:0:2} hrs=${hrs#0}
min=${time:3:2} min=${min#0}
echo "Total time elapsed $((hrs*60+min)) minutes"

Here's a variant that uses 10# to force base 10:

time="08:09"
hrs=${time:0:2}
min=${time:3:2}
echo "Total time elapsed $((10#$hrs*60 + 10#$min)) minutes"

> locmin=hrs*60+min

I also strongly discourage the use of "declare -i".  It's very confusing.
If you want to do arithmetic, it's easier for the reader to understand
what's happening if you actually use arithmetic syntax, rather than
relying on the reader to remember that you used "declare -i" 600 lines
ago, or in a dotted-in script.

locmin=$((hrs*60+min))



reply via email to

[Prev in Thread] Current Thread [Next in Thread]