Home > Back-end >  Match any symbol in Bash case statement
Match any symbol in Bash case statement

Time:09-19

I have a string of pattern <digit>, <digit>. I want to check whether it has:

  • Two zeroes
  • Left zero and right non-zero
  • Left non-zero and right zero
  • Anything else

I have tried to do this with the following code:

case ... in
    "0, 0") ... ;;
    "0, ?") ... ;;
    "?, 0") ... ;;
    *)      ... ;;
esac

But it is only matching "two zeroes" and "any other" cases. How can I fix that?

CodePudding user response:

To get the interpretation of the globs, they must be outside of the double quotes:

#!/bin/sh

case $1 in

  "0, 0")  echo case 1 ;;
  "0, "?)  echo case 2 ;;
   ?", 0") echo case 3 ;;
  *)       echo default ;;

esac

Examples:

$ b.sh "0, 0"
case 1
$ b.sh "0, 1"
case 2
$ b.sh "3, 1"
default
$ b.sh "3, 0"
case 3

If you want to match only digits, "?" glob is too permissive as it matches any char not necessarily a digit:

$ b.sh "a, 0"
case 3

To be more restrictive, intervals can be used to match only digits:

#!/bin/sh

case $1 in

  "0, 0")      echo case 1 ;;
  "0, "[0-9])  echo case 2 ;;
   [0-9]", 0") echo case 3 ;;
  *)           echo default ;;

esac
  •  Tags:  
  • bash
  • Related