bashcasemultiple-results

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?


Solution

  • 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