4

how to make switch execute 2 cases?

I tried with the following code, but it execute only the first case

#!/bin/sh
action="titi"

case "$action" in
    toto|titi)
    echo "1_$action"
    ;;
    tata|titi)
    echo "2_$action"
    ;;
esac
MOHAMED
  • 41,599
  • 58
  • 163
  • 268

4 Answers4

12

The case statement in bash executes the commands in the COMMAND-LIST for the first match only.

However, In bash version 4 or later introduced the ;& terminator. The ;;& operator is like ;;, except the case statement doesn't terminate after executing the associated list - Bash just continues testing the next pattern as though the previous pattern didn't match. Using these terminators, a case statement can be configured to test against all patterns, or to share code between blocks, for example.

Reference: Excerpt taken from http://wiki.bash-hackers.org/syntax/ccmd/case

So if you have bash v 4 or later this would give your desired result:

#!/bin/sh
action="titi"

case "$action" in
    toto|titi)
    echo "1_$action"
    ;;&
    tata|titi)
    echo "2_$action"
    ;;
esac
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
1

Maybe consider titi a default value to execute if no pattern is matched

#!/bin/sh
action="titi"

case "$action" in
    toto)
    echo "1_$action"
    ;;
    tata)
    echo "2_$action"
    ;;
    *)
    echo "1_$action"
    echo "2_$action"
esac
mirkobrankovic
  • 2,389
  • 1
  • 21
  • 24
1

based on @josay comment, this is called "fall through" and could be done with bash script by using ;;& instead of ;; in the first case. But the "fall through" works only if the bash version is 4.0 or later

Following, Source code updated with the "fall through"

#!/bin/sh
action="$1"

case "$action" in
    toto|titi)
    echo "1_$action"
    ;;&
    tata|titi)
    echo "2_$action"
    ;;
esac
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
0

Use if twice and it matches twice.

if [ "$action" = 'toto' -o "$action" = 'titi' ]; then
    echo "1_$action"
fi
if [ "$action" = 'tata' -o "$action" = 'titi' ]; then
    echo "2_$action"
fi

If you need to use case, how about using function

function f1
{
    echo "1_$action"
}

function f2
{
    echo "2_$action"
}

case "$action" in
    titi)
    f1
    f2
    ;;
    toto)
    f1
    ;;
    tata)
    f2
    ;;
esac
kamae
  • 1,825
  • 1
  • 16
  • 21