Is it possible to combine two conditions in switch case for Bash script?

Viewed 781

Suppose I want to read two inputs say x and y. And as per values of them I want to execute switch case in Bash script.

Say 4 combinations of inputs are

  1. x=0, y=0,
  2. x=0, y=1,
  3. x=1, y=0,
  4. x=1, y=1.

But I don't know how to do it using script. I have tried the code but its getting syntax error. Is it possible to combine two conditions in switch case for Bash script?

echo "enter x"
read x

echo "enter y"
read y

case "$x" "$y" in
    "zero" "zero") echo "condtion 1"
    ;;
    "zero" "one") echo "conditon 2"
    ;;
    "one" "zero" ) echo "condition 3"
    ;;
    "one" "one") echo "condition 4"
    ;;
esac
3 Answers

You can think of $x$y as a binary number.

#! /bin/bash

read -p 'enter x: ' x
read -p 'enter y: ' y

case $((2#$x$y)) in
  0) echo 'condition 1';;
  1) echo 'condition 2';;
  2) echo 'condition 3';;
  3) echo 'condition 4';;
esac

This works up to 64 different states:

$ echo $((64#11))
65

You could use a separator:

echo "enter x"
read x

echo "enter y"
read y

SEP=":::"
case "${x}${SEP}${y}" in
    "zero${SEP}zero") echo "condtion 1"
    ;;
    "zero${SEP}one") echo "conditon 2"
    ;;
    "one${SEP}zero" ) echo "condition 3"
    ;;
    "one${SEP}one") echo "condition 4"
    ;;
esac

Case is about pattern matching, check this out:

$ case "a" in
>       b) echo fail;;
>       a) echo ok  ;;
> esac
ok

$ case "b" in
>       b) echo fail;;
>       a) echo ok  ;;
> esac
fail

So you just need to pass a pattern to the case. Which in your case could be like this:

read -p "enter x(0|1): " x
read -p "enter y(0|1): " y
    
case "$x$y" in
       00) echo "condition 1";;
       01) echo "condition 2";;
       10) echo "condition 3";;
       11) echo "condition 4";;
esac

And a separator is needed for a better readability(mostly).

case "$x|$y" in
       0|0) echo "condition 1";;
       0|1) echo "condition 2";;
       1|0) echo "condition 3";;
       1|1) echo "condition 4";;
esac
Related