help-bash
[Top][All Lists]
Advanced

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

Verifying numeric values


From: tolugboji
Subject: Verifying numeric values
Date: Tue, 19 Oct 2021 16:00:55 +0000

‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐

On Tuesday, October 19th, 2021 at 3:49 PM, tolugboji <tolugboji@protonmail.com> 
wrote:

> ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
>
> On Tuesday, October 19th, 2021 at 11:20 AM, Greg Wooledge greg@wooledge.org 
> wrote:
>
> > On Mon, Oct 18, 2021 at 11:44:16PM -0400, Andy Chu wrote:
> >
> > > On Mon, Oct 18, 2021 at 11:25 PM Greg Wooledge greg@wooledge.org wrote:
> > >
> > > > On Mon, Oct 18, 2021 at 11:10:32PM -0400, Andy Chu wrote:
> > > >
> > > > > Try this:
> > > > >
> > > > > is_valid() {
> > > > >
> > > > > local x=$1
> > > > >
> > > > > local b=$(( 1 <= x && x <= 255 ))
> > > > >
> > > > > return $(( ! b )) # 0 is true, 1 is false
> > > > >
> > > > > }
> > > >
> > > > Using un-validated input in a math context is a code injection in bash.
> > > >
> > > > Given that the purpose of this function is to validate the input, one
> > > >
> > > > must assume the input may be malicious.
> > >
> > > Yes good point, I wrote about that here:
> > >
> > > https://www.oilshell.org/blog/2019/01/18.html#a-story-about-a-30-year-old-security-problem
> > >
> > > In that case I would turn it into something like this
> > >
> > > is_valid() {
> > >
> > > local x=$1
> > >
> > > if [[ $x =~ [[:digit:]]+ ]]; then
> > >
> > > local b=$(( 1 <= x && x <= 255 ))
> > >
> > > return $(( ! b )) # 0 is true, 1 is false
> > >
> > > else
> > >
> > > return 1
> > >
> > > fi
> > >
> > > }
> > >
> > > (Or use 'expr' if you care about portability to non-bash shells.)
> >
> > You can use 'case'.
> >
> > In sufficiently new versions of bash, you can replace your regex with
> >
> > an extended glob -- yes, even if "extglob" is not enabled. In newer
> >
> > versions of bash, extended globs are always allowed inside [[.
>
> > [[ $x = +([[:digit:]]) ]]
> >
> > Or see https://mywiki.wooledge.org/BashFAQ/054 for other ideas.
> > Whoever put that "Avoid [[:digit:]]" sentence on there... well,
> > it's a public wiki, so you get all kinds of edits.
>
> Using ( +([[:digit:]]) ) in a case statement did not work well
> for me even with shopt -s extglob
>
> Have not been able to resolve the problem.
>
> So I switced to using
>
> [[ "$var" =~ ^[0-9]+$ ]]
>
> Have not tried with [[ $x = +([[:digit:]]) ]], but
> if it works, I like it.


Have tested [[ $x = +([[:digit:]]) ]] and it works well.
There must be something happening with using +([[:digit:]])
in a case statement which is not straightforward.





reply via email to

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