93

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

Example:

int a = 2;
switch(a)
{
   case 1:
      print "quick ";
   case 2: 
      print "brown ";
   case 3: 
      print "fox ";
      break;
   case 4:
      print "jumped ";
}

would print "brown fox".

However the same code in bash

A=2
case $A in
2)
  echo "QUICK"
  ;&
2)
  echo "BROWN"
  ;&
3)
  echo "FOX"
  ;&
4)
  echo "JUMPED"
  ;&
esac

only prints "BROWN"

How do I make the case statement in bash "fall through" to the remaining conditions like the first example?

(edit: Bash version 3.2.25, the ;& statement (from wiki) results in a syntax error)

running:

test.sh:

#!/bin/bash
A=2
case $A in
1)
  echo "QUICK"
  ;&
2)
  echo "BROWN"
  ;&
3)
  echo "FOX"
  ;&
esac

Gives:

./test.sh: line 6: syntax error near unexpected token ;' ./test.sh:
line 6:
;&'

1

6 Answers 6

79

Try this:

case $VAR in
normal)
    echo "This doesn't do fallthrough"
    ;;
fallthrough)
    echo -n "This does "
    ;&
somethingelse)
    echo "fall-through"
    ;;
esac
4
  • 3
    When I try this, I get syntax error near unexpected token `;' on the line with ;&. Why is this? Commented Feb 13, 2020 at 0:52
  • 7
    @CameronHudson because you're using a version of Bash earlier than 4.0
    – Josh
    Commented Feb 13, 2020 at 21:48
  • 1
    This is Great!!! It's solved so many problems for me.
    – RonJohn
    Commented Oct 7, 2022 at 14:34
  • For a possible caveat that is on the bash versions, refer to the accepted answer. Commented Feb 15 at 7:29
58

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.)

13
  • Wow! Thank you, I see now my 'new' MacBookPro 2012 has a very old 2007 Bash: GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin12) Commented Dec 7, 2013 at 18:07
  • 9
    @AnneTheAgile, yes. bash 3.2 is GPLv2, bash 4.0 (and newer) is GPLv3, and Apple "doesn't like" GPLv3 (en.wikipedia.org/wiki/GPL_v3#Legal_Barrier_to_App_Stores). Though you can easily get a recent bash with homebrew or macports or similar, of course.
    – geirha
    Commented Dec 9, 2013 at 10:02
  • 2
    @Will not in bash and sh, since shell variables share the namespace with environment variables and special shell variables.
    – geirha
    Commented Jun 10, 2017 at 5:32
  • 2
    @Will, part of "avoid namespace conflicts" is staying out of the namespace that POSIX specifies for use for variables meaningful to the operating system and shell. That namespace is defined by the standard as the set of all-caps names; see pubs.opengroup.org/onlinepubs/9699919799/basedefs/…, keeping in mind that environment and shell variables share a namespace. Commented Jul 24, 2019 at 20:04
  • 1
    @user2066657: 12 is for Bash 4, 15 for 3.2. But to the point: the reason Apple blocks 4.0 is not because it's less "enterprisey" than 3.2, it's because of GPL3. It has nothing to do with stability, maturity or security. It's not a technical decision, please stop implying so.
    – MestreLion
    Commented Apr 21, 2021 at 7:10
14

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

Here's a proof of concept: https://www.onlinegdb.com/0ngLPXXn8

17
  • 2
    "real sh" is what, pre-POSIX (aka 1970s-era-syntax) Bourne? Commented Jul 24, 2019 at 20:06
  • 4
    @CharlesDuffy /bin/sh is a Bourne shell, the common base for BASH, DASH, ASH and also for the POSIX standard. Each of these shells support additional features, some unique to the shell but they are all SH compatible, unlike some other shells (csh and tcsh are not, zsh is only partially)
    – Mecki
    Commented Jul 27, 2019 at 15:34
  • 5
    Bourne is a shell from the 1970s. POSIX sh is a specification from 1991. /bin/sh on modern systems is POSIX, not Bourne. To pick an easy-to-test-for difference, echo hello ^ cat will emit hello on Bourne, because ^ is a pipe character there; whereas in a POSIX-compliant shell, it emits hello ^ cat as output, because the ^ is parsed as an argument to echo. Commented Jul 27, 2019 at 15:35
  • 2
    (Incidentally, the ^-as-a-pipe-character difference is the one that GNU autoconf uses to distinguish whether it's on Bourne or POSIX sh; that said, the POSIX spec generally took a lot of inspiration from early ksh, and thus codified behaviors that were originally ksh extensions). Commented Jul 27, 2019 at 15:41
  • 4
    Definitely valid answer. Many embedded machines ship with ash and even sh in ubuntu is dash. For those shells this answer is valid. Have no idea why this is downvoted and why are we arguing whether non bash, sh is relevant...It is even quite elegant and idiomatic Commented Dec 10, 2019 at 16:16
3

Use a sequence of case statements with pattern alternation:

#!/bin/sh

a="2"
case "$a" in
    "1")
        echo "QUICK"
        ;;
esac
case "$a" in
    "1" | "2")
        echo "BROWN"
        ;;
esac
case "$a" in
    "1" | "2" | "3")
        echo "FOX"
        ;;
esac
case "$a" in
    "4")
        echo "JUMPED"
        ;;
esac

Benefits:

  • Follows the format of the original question
  • Works with any POSIX-compliant sh, including old versions of Bash
  • Unordered string values of a such as "apple", "pear", "banana", "tree" will work
  • Control flow is straightforward without backward branches

Disadvantages:

  • More characters are needed since there are four case statements instead of just one

Note that lowercase a is better than uppercase A for non-environment variables and that $a as well as the case patterns should be quoted for the general case where a might have spaces in it. Quoting can be removed for simple cases.

1
  • I really like this approach, because of its readability, even with the burden of extra characters. I think people who don't have a lot of bash experience will be less likely to be confused, and more likely to intuitively understand how it works and how to make changes. Note that cases that do not need fallthrough can be combined in the same case statement. You only need a separate case statement where a 'break' would be omitted in a 'switch' statement..
    – Bob Kerns
    Commented Apr 6, 2023 at 22:33
1

While @cjfp's answer with multiple case statements would be my preferred approach to actually doing fallthrough, I usually avoid the issue entirely.

The benefits of this are not obvious for trivial examples, but when each case becomes complex, fallthrough becomes a nightmare to follow.

The solution is to simplify the case statement with functions.

Approach #1

#!/bin/bash

quick() {
  echo "QUICK"
}
brown() {
  echo "BROWN"
}
fox() {
  echo "FOX"
}
jumped() {
  echo "JUMPED"
}

qbf() {
  case "$1" in
    1)
      quick
    ;;
    2)
      quick; brown
    ;;
    3)
      quick; brown; fox
    ;;
    4)
      quick; brown; fox; jumped
    ;;
  esac
}
qbf "$1"

Of course, for large numbers of cases, this can get out of hand. But it need not grow linearly.

Let's add "over the lazy dog". I'll omit the echo-functions; you get the idea.

Approach #2

# Continuing from above
lazydog() {
  case "$1" in
  5)
    qbf "$1"; over
  ;;
  6)
    qbf "$1"; over; the
  ;;
  7)
    qgf "$1"; over; the; lazy
  ;;
  8)
   qbf "$1"; over; the; lazy; dog
  ;;
  esac
}

But this gets out of hand, too. But really long case statements are already problematic. We'd like to avoid adding any redundancy at all.

So here's how we can do that! (Reverting to the original example for brevity).

Approach #3

#!/bin/sh

foxy() {
  case "$1" in
    1)
      echo "QUICK"
      ;;
    2)
      foxy 1; echo "BROWN"
    ;;
    3)
      foxy 2; echo "FOX
    ;;
    4)
      foxy 3; echo "JUMPED"
    ;;
  esac
}

foxy "$1"

What goes on here is that fallthrough is replaced with invoking the prior case recursively before the current one.

I normally use approach #1 for simple cases. (I probably use @cjfp's approach at times without even thinking about it in very simple cases).

If I get to the level I'd want approach #2, I'd just skip ahead to the more general approach #3. #2 is introduced as a stepping-stone to recursion.

But really, if I get to #3, I'm considering writing it in something other than bash. But sometimes bash is a constraint, thanks to its incredible ubiquity.

But I try to avoid fallthrough even in languages that support it.

It's a lot more clear to think of each case separately, with the option to include the prior case. It's a lot more powerful, as well. You can have all later cases include case 1 without including cases 2...n-1.

Between breaking out the cases as functions that can be invoked independently, and recursive invocation, each case can be composed freely from a palette of independent functions and/or complete sub-cases.

switch only looks attractive for very simple situations, with a very linear structure.

Between the options I present here, along with @cjfp's approach with multiple case statements, or a state-machine approach such as in @Meki's answer, the lack of a case statement is not much of a burden.

The risks of accidental fallthrough outweigh the benefits; thus language designers tend to shy away from including switch, despite its familiarity due to certain widely-used languages. It's not been a part of any language I've had a part in designing. I can't take credit; it was widely recognized even before my time, and I'm retired now.

I hope that my answer, along with the others here, give you a different way of thinking about the problem. I'd avoid the ';&' feature. Even aside from compatibility problems you are giving up the semantic safety offered by vanilla 'case'.

1
  • In 20 years I don't think I've ever considered or even come across something like #3. I'm not sure what that says about me, but I guess it's good news either way. A few practical examples would be super, if you find the time and care to Commented Sep 9 at 15:29
-1

bash switch with fallthrough, implemented with function and flag

#! /bin/sh

switch_fallthrough() {
  [ $# = 0 ] && { echo no value >&2; return; }
  local f= # fall through
  [ "$1" = 1 ] && { echo quick; f=1; }
  [ $f ] || [ "$1" = 2 ] && { echo brown; f=1; }
  [ $f ] || [ "$1" = 3 ] && { echo fox; return; }
  [ $f ] || [ "$1" = 4 ] && echo jumped
  return 1 # error = no case did match
}

switch_fallthrough "2"
# brown
# fox
1
  • this is neither a regex nor a fallthrough, sorry
    – xeruf
    Commented Feb 6, 2022 at 18:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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