help-bash
[Top][All Lists]
Advanced

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

Re: case statement with non-consecutive numbers


From: Greg Wooledge
Subject: Re: case statement with non-consecutive numbers
Date: Thu, 15 Apr 2021 13:24:44 -0400

On Thu, Apr 15, 2021 at 07:13:27PM +0200, pauline-galea@gmx.com wrote:
> > case $input in
> >   [2-68-9]) echo "yeah, that's good, screw 7";;
> > esac
> 
> I struggle with what the above means, I'm afraid.

[2-6] is a glob-type pattern (or "glob" for short, as long as we're
clear that it's being used in a context where bash doesn't expand it
to a list of filenames).  Specifically, it's a "range expression",
meaning it matches any single character within the range "2" to "6".

Let's actually go back even farther than this.

The glob [ab] matches either "a" or "b".
The glob [abcde] matches one of "a", "b", "c", "d" or "e".

Since it's pretty common to want to match one of several characters that
are consecutive within the alphabet, we have the range expression
shorthand:

The glob [a-e] matches one of "a", "b", "c", "d" or "e" -- but ONLY IF
the current locale is set to "POSIX" or "C", or if we're using a special
bash option that treats range expressions as if we were in the POSIX locale.

But you can also combine these.

The glob [a-eqz] matches one of "a", "b", "c", "d", "e", "q" or "z".

> > Fear not!  You can just use more than one pattern.
> >
> > case $input in
> >   [3-5]|9|1[0-3]) echo "yeah, that's good";;
> > esac
> 
> Means I can use "|" just as for strings.

They *are* strings.  That's the entire point of this.  You are matching
strings against strings.  The fact that the strings happen to be made up
of digits is mostly irrelevant.

The glob [3-5] matches any of "3", "4" or "5".

> Doing more work on this, it looks like using commas also works
> 
>       case $k in
>         [1-2,4-5,7])  printf "%-21s" $s   ;;
>         [3,6,8])      printf "%-21s\n" $s ;;
>       esac
> 
> Would that be correct?

The glob [3,6,8] matches any of "3", ",", "6" or "8".

You probably did not intend to match commas in your input.  Get rid of
those.



reply via email to

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