Issue
This Content is from Stack Overflow. Question asked by Max Smirnov
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
- any other
I have tried to this with following code:
case ... in
"0, 0") ... ;;
"0, ?") ... ;;
"?, 0") ... ;;
*) ... ;;
esac
But it is only matches “two zeroes” and “any other” cases. How can I fix that?
Solution
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
This Question was asked in StackOverflow by Max Smirnov and Answered by Rachid K. It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.