bug-bash
[Top][All Lists]
Advanced

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

Re: "printf %d ''" should diagnose the empty string


From: Greg Wooledge
Subject: Re: "printf %d ''" should diagnose the empty string
Date: Mon, 10 Feb 2025 07:14:36 -0500
User-agent: Mutt/1.10.1 (2018-07-13)

On Mon, Feb 10, 2025 at 09:50:01 +0100, Phi Debian wrote:
> On Sat, Feb 8, 2025 at 8:51 AM Robert Elz <kre@munnari.oz.au> wrote:
> > There are a gazillion different ways of getting rid of the octal
> > conversion "problem", one I prefer in cases where I know the value
> > is 2 digits, always, but might be 0n for 0<=n<=9, is  $(( 1$x - 100 ))
> >
>  gazillion++
> You say "I know the value is 2 digits" you forgot to say in base 10 but it
> was kinda implicit in the thread, then a more general one not limited to 2
> decimal digit accepting leading 0 you could simply do $((10#$i))

This issue comes up all the time.

Both of these solutions have limitations on what kind of input they'll
accept.  Robert's only works on two-digit unsigned inputs.  Phi's
works only on unsigned inputs of any length.

hobbit:~$ var=-023
hobbit:~$ echo "$((1$var - 100))"
-118
hobbit:~$ echo "$((10#$var))"
bash: 10#: invalid integer constant (error token is "10#")

The following line noise is the best *general* answer we've found
so far:

    $((${num%%[!+-]*}10#${num#[-+]}))

See:

<https://mywiki.wooledge.org/ArithmeticExpression#Leading_Zeros_and_Base_Selection>
<https://lists.gnu.org/archive/html/bug-bash/2018-07/msg00033.html>




reply via email to

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