19

Have I got enough (or perhaps too many) ;; terminators in this bash script containing nested case's?

case "$1" in
OK)
    # Nothing needs done
    echo -n "OK:1" ;;

CRITICAL)

    case "$2" in
    SOFT)
        case "$3" in
        1|2) 
            soft_reset_pool.sh ;;
        esac ;;

    HARD)
        case "$3" in
        1|2)
            hard_reset_pool.sh ;;

        3|4)
            hard_reset_service ;;

        esac ;;
    esac ;;      
esac

It's been a few years since I did any bash in anger.

2 Answers 2

46

It's easier to keep track if you use sensible indentation on the ;;s.

case "$1" in
OK)
    # Nothing needs done
    echo -n "OK:1"
    ;;

CRITICAL)

    case "$2" in
    SOFT)
        case "$3" in
        1|2) 
            soft_reset_pool.sh
            ;;
        esac
        ;;

    HARD)
        case "$3" in
        1|2)
            hard_reset_pool.sh
            ;;

        3|4)
            hard_reset_service
            ;;

        esac
        ;;
    esac
    ;;
esac

They match up fine, every case label) having a terminating ;;

That said, sometimes it's easier and/or clearer to collapse everything into a non-nested case:

case "$1:$2:$3" in

OK:*)
    # Nothing needs done
    echo -n "OK:1"
    ;;

CRITICAL:SOFT:[12])
    soft_reset_pool.sh
    ;;

CRITICAL:HARD:[12])
    hard_reset_pool.sh
    ;;

CRITICAL:HARD:[34])
    hard_reset_service
    ;;

esac
1
  • Collapsing the case statement was the best idea, in my situation.
    – RonJohn
    Commented Aug 7, 2022 at 14:15
1

If you have to deal with multiple pattern strings :

Imagine $3 is a string.

...
CRITICAL:HARD:@("A"|"B"|"C"))
...

In Bash you need to add the following on the script :

shopt -s extglob

Thanks to Hauke Laging for the tip.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .