help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] Brace expansions in if statement


From: Felipe Salvador
Subject: Re: [Help-bash] Brace expansions in if statement
Date: Wed, 4 Apr 2018 18:45:24 +0200
User-agent: NeoMutt/20170113 (1.7.2)

On Fri, Mar 30, 2018 at 08:29:23AM -0400, Greg Wooledge wrote:
> On Fri, Mar 30, 2018 at 12:40:19AM +0200, João Eiras wrote:
> > if [[ "$(echo " "tty{0..10}" ")" == *" $GTTY "* ]]; then
> 
> Bleh!
> 
> There is no need to fork a subshell to generate a list of words
> concatenated into a string with spaces around them so that you can
> do a brute force substring match of " foo " against " foo bar baz ".
> That's simply unnecessary, and inefficient, and outright *weird*,
> compared to the more obvious alternatives.
> 
> The answer previously given is sufficient, and is much nicer in my
> opinion:
> 
>   case $GTTY in
>     tty[0-9]|tty10) ...

Thank you all, I've opted for case. 


> If you have an allergy to case for some reason, and absolutely *insist*
> that it simply *must* with be done an if, you can use extglob matching:
> 
>   if [[ $GTTY = tty@([0-9]|10) ]]; then ...
> 
> Or even ERE matching:
> 
>   if [[ $GTTY =~ ^tty([0-9]|10)$ ]]; then ...
> 
> Because I know how much some people like their EREs.
> 
> Or hell, you could even use two matches:
> 
>   if [[ $GTTY = tty[0-9] || $GTTY = tty10 ]]; then ...
> 
> That way you don't have to worry about whether extglob is enabled or
> disabled or enabled-implicitly-inside-[[ only or anything else.
> And that's *still* shorter and more efficient than the $(echo) thing.
> Plus, it's the most readable one.

-- 
Felipe Salvador



reply via email to

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