Search code examples
bashshcase-statement

Is there more elegant way to write statement with overlapping (nested) alternatives?


I want to write case statement with overlapping alternatives.

Quick search on the internet gives me examples with alternatives which is unique and not overlapping, smth like:

case $var in
    a) <code> ;;
    b) <code> ;;
    *) <code> ;;
esac

But I need scenario where one alternative contains several alternatives and additional work. I figure it this way:

case $loglevel in
    [0-7]) <code>
           case $loglevel in
                [0-3] <redirect to /dev/console> 
                ;;
                [4-7] <redirect to /dev/null> 
                ;;
           esac
    ;;
    *) <code> ;;
esac

I guess is there any more elegant or rational way to do this. It seems for me that nested case statement for such simple scenario is too much.


Solution

  • If your shell is modern enough, you can use ;;& instead of ;; to try the following conditions even if the current one succeeded:

    #! /bin/bash
    loglevel=$1
    case $loglevel in
        ([0-7]) echo 0..7
                ;;&
        ([0-4]) echo 0..4
                ;;
        ([5-7]) echo 5..7
                ;;
        (*) echo Ohter
    esac
    

    Which gives

    ▏~ $ 1.sh 1
    0..7
    0..4
    ▏~ $ 1.sh 6
    0..7
    5..7