bash nested case syntax and ;; terminators

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x