14

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.

| improve this question | | | | |
38

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
| improve this answer | | | | |
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.

| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.