help-bash
[Top][All Lists]
Advanced

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

Re: case $var in $list) issue


From: Greg Wooledge
Subject: Re: case $var in $list) issue
Date: Fri, 1 Nov 2024 11:50:39 -0400

On Fri, Nov 01, 2024 at 11:20:31 -0400, Zachary Santer wrote:
> On Thu, Oct 31, 2024 at 9:55 PM #!microsuxx <fxmbsw7@gmail.com> wrote:
> >
> > ~ $ echo $short
> > li|la|ds|fs|ac|U|S|u|s|r|i|f|c
> 
> declare -a short=( li la ds fs ac U S u s r i f c )
> match='false'
> for pattern in "${short[@]}"; do
>   if [[ ${whatever} == ${pattern} ]]; then
>     match='true'
>     break
>   fi
> done
> 
> Probably the way to go if your list of patterns is determined dynamically.

Yeah, but in my experience, a lot of people just *abhor* writing a loop.
They'll do anything else.  It's like a religion or something.

(Also, you should quote "$pattern" there if each list element is to be
treated as a fixed string instead of a glob.)

> If the case construct didn't require a | between different patterns in
> the same pattern list, then you could just expand ${short[@]} there.

We've already learned that you can use an extglob to achieve the desired
result (matching a short string against a list of short strings in a
single matching step).  Chet even explained why it works.

> > ~ $ echo $short
> > li|la|ds|fs|ac|U|S|u|s|r|i|f|c

shopt -s extglob
shorts="@($short)"
case $input in $shorts) echo match;; *) echo no match;; esac
    ... or the [[ ]] equivalent.

> Using [[  ]] in a for loop is going to be easier to wrap your head
> around

I'm assuming that writing a simple script that works, is efficient, and
is readable is NOT the goal here.  It very rarely is.

The goal is most likely one of:

 * Do it using a special dedicated feature that looks cool.
 * Do it in a clever way instead of an obvious way.
 * Make it short.

We do get the golfer mentality sometimes, though I don't think xmb falls
into that particular group.  Usually it's one of the first two.



reply via email to

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