[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] Brace expansions in if statement
From: |
Greg Wooledge |
Subject: |
Re: [Help-bash] Brace expansions in if statement |
Date: |
Fri, 30 Mar 2018 08:29:23 -0400 |
User-agent: |
NeoMutt/20170113 (1.7.2) |
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) ...
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.