简体   繁体   中英

Bash case $var in multiple hits

shopt -s extglob 
CONDITION1="@(*cheese*|*milk*|*cream*)"
CONDITION2="@(*potato*|*rice*|*pasta*)"

myvar1="pasta with cheese"

case ${myvar1} in
${CONDITION1} )
        echo DAIRY
        ;;
${CONDITION2} )
        echo CARBS
        ;;
* )
        echo HUNGRY
        ;;
esac

result of this script is echo DAIRY

I need to change above code so it echoes: DIARY CARBS

Is that possible?

Use ;;& instead of ;; if you want this behaviour.

That said, fall-through behavior will mean that you get HUNGRY unconditionally. I'd suggest setting a flag on matches and checking for it before emitting HUNGRY .

So:

myvar1="pasta with cheese"; matched=0
case $myvar1 in
  *cheese*|*milk*|*cream*)
     echo DAIRY; matched=1 ;;&
  *potato*|*rick*|*pasta*)
     echo CARBS; matched=1 ;;&
esac
(( matched )) || echo HUNGRY

That said, it would be easy enough to make this code compliant with POSIX sh by splitting into multiple case statements (and, again, not using extglobs):

myvar1="pasta with cheese"; unset matched
case $myvar1 in *cheese*|*milk*|*cream*) echo DAIRY; matched=1 ;; esac
case $myvar1 in *potato*|*rick*|*pasta*) echo CARBS; matched=1 ;; esac
[ "$matched" ] || echo HUNGRY

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM