help-bash
[Top][All Lists]
Advanced

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

Best method for converting a string to a number in bash


From: Stan Marsh
Subject: Best method for converting a string to a number in bash
Date: Thu, 05 Feb 2026 08:30:30 -0700

The specific case that I'm concerned with is when the string is
something like:

    123abc

And I want the result to be 123. I.e., convert as much as you can,
ignore the rest. This is basically what the C library function atoi()
(and similar) do. It is also what AWK does. But many languages,
including bash, insist on reporting this as an error.

Below is my current solution - which works well enough - but I think
there is a more bash-y way to do it (that doesn't require dumping
stderr), but I can't remember it now. Note: Not interested in anything
that uses any external program, such as "awk" or "perl" or whatever;
should be all bash builtins.

poof () 
{ 
    printf "$@" 2> /dev/null;
    return 0
}

bash's printf() outputs the answer, but then generates a (bogus) error
message, so the above does the trick.

=================================================================================
Please do not send me replies to my posts on the list.
I always read the replies via the web archive, so CC'ing to me is unnecessary.

When responding to my posts, please try to refrain from giving bureaucratic 
answers.
If you have nothing useful to say, then just click Next and go on.



reply via email to

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