Case statement fallthrough?

后端 未结 3 933
长情又很酷
长情又很酷 2020-12-05 03:57

In popular imperative languages, switch statements generally \"fall through\" to the next level once a case statement has been matched.

Example:

int         


        
相关标签:
3条回答
  • 2020-12-05 04:14

    Try this:

    case $VAR in
    normal)
        echo "This doesn't do fallthrough"
        ;;
    fallthrough)
        echo -n "This does "
        ;&
    somethingelse)
        echo "fall-through"
        ;;
    esac
    
    0 讨论(0)
  • 2020-12-05 04:22

    The ;& and ;;& operators were introduced in bash 4.0, so if you want to stick with a five year old version of bash, you'll either have to repeat code, or use ifs.

    if (( a == 1)); then echo quick; fi
    if (( a > 0 && a <= 2)); then echo brown; fi 
    if (( a > 0 && a <= 3)); then echo fox; fi
    if (( a == 4)); then echo jumped; fi
    

    or find some other way to achieve the actual goal.

    (On a side note, don't use all uppercase variable names. You risk overwriting special shell variables or environment variables.)

    0 讨论(0)
  • 2020-12-05 04:27

    Using ;& is not very portable, as it requires bash (not ash, dash, or any other minimal sh) and it requires at least bash 4.0 or newer (not available on all systems, e.g. macOS 10.14.6 still only offers bash 3.2.57).

    A work around that I consider much nicer to read than a lot of if's is loop and modify the case var:

    #!/bin/sh
    
    A=2
    A_BAK=$A
    while [ -n "$A" ]; do
        case $A in
            1)
                echo "QUICK"
                A=2
                ;;
    
            2)
                echo "BROWN"
                A=3
                ;;
    
            3)
                echo "FOX"
                A=4
                ;;
    
            4)
                echo "JUMPED"
                A=""
                ;;
        esac
    done
    A=$A_BAK
    
    0 讨论(0)
提交回复
热议问题