bug-bash
[Top][All Lists]
Advanced

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

Re: value too great for base (error token is "0008")


From: Greg Wooledge
Subject: Re: value too great for base (error token is "0008")
Date: Wed, 4 Nov 2009 08:23:08 -0500
User-agent: Mutt/1.4.2.3i

On Tue, Nov 03, 2009 at 05:37:45PM -0700, Bob Proulx wrote:
> Dobromir Romankiewicz wrote:
> > bash: 0008: value too great for base (error token is "0008").

> Numbers with leading zeros are read as octal constants.  Octal is
> composed of '0' through '7'.  The number '8' is too large to be an
> octal number.
> 
>   $ echo $((0008))
>   bash: 0008: value too great for base (error token is "0008")
> 
> To have the number read as a decimal number the leading zeros must be
> removed.
> 
>   $ echo $((8))
>   8

If removing the leading zeroes would be difficult for you, then you can
force the arithmetic expression to use base 10 by prefixing the variable
with "10#".  Thus:

  month=$(date +%m)     # Can produce "08" etc.
  next_month=$(( (10#$month == 12) ? 1 : 10#$month+1 ))
  echo $next_month

On the other hand, removing a single leading zero is not difficult:

  month=$(date +%m) month=${month#0}   # Removing leading 0
  next_month=$(( ($month == 12) ? 1 : $month+1 ))

Removing multiple leading zeroes, however, requires either a loop, or the
use of extended globs.  A variant of this question (removing leading/trailing
spaces) appears at <http://mywiki.wooledge.org/BashFAQ/067>.  Although it
looks like someone removed my loop solution... grrr.

> Note also that the use of $[expression] for $((expression)) is
> documented as deprecated and to be removed in a future version.
> Better to use $((expression)) instead.

$((...)) is also POSIX-compliant.  Please do switch.




reply via email to

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