-1

I want something like this:

time="1m"
case "$time" in
    *h*) 
    *m*) 
    *s*) 
        echo "handling several cases for h, m, s tokens" ;;
    *)
        echo "handling other cases" ;;
esac

How to achieve this for POSIX shell?

14
  • 2
    Does this answer your question? AND operator in case statement?     No, it’s not the same question, but it does contain the answer to this question. Commented May 10, 2024 at 23:30
  • 2
    Note that we explicitly allow and encourage self-answered questions, and we tolerate (if you’ll pardon the phrase) “dumb questions”.  But asking and self-answering a question that is trivially answered by reading the documentation strikes me as abuse of the mechanism. Commented May 10, 2024 at 23:30
  • I kindly disagree about "dumb question". Dumb question in my understanding is the question answer to which can be easily found. And I have not easily succeeded with this. The first three results from googling "shell case syntax" do not mention syntax for | (OR) operator. Here on Unix Stackexchange was only related question that you've mentioned - AND operator in case statement. And thanks to it I found right link to the case syntax. Commented May 11, 2024 at 9:08
  • @G-ManSays'ReinstateMonica' That is why I thought that It is right thing to do to a bit simplify search of the answer for the next researchers by creating this question. Commented May 11, 2024 at 9:09
  • 1
    @AntonSamokat for the latter you are welcome to suggest an edit to that question Commented May 11, 2024 at 11:54

1 Answer 1

-1

The syntax of the case command is:

case word in
    [(] pattern1 ) compound-list ;;
    [[(] pattern[ | pattern] ... ) compound-list ;;] ...
    [[(] pattern[ | pattern] ... ) compound-list]
esac

Syntax for case also can be printed in bash by the command below (it is suitable for POSIX shell as well):

$ help case
case: case WORD in [PATTERN [| PATTERN]...) COMMANDS ;;]... esac

Execute commands based on pattern matching.

Selectively execute COMMANDS based upon WORD matching PATTERN.  The
`|' is used to separate multiple patterns.

Exit Status:
Returns the status of the last command executed.

Syntax in man bash:

case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esac

can be found by ^ *case pattern.

Example of usage:

time="1m"
case "$time" in
    *h*|*m*|*s*)
        echo "first case"
        echo "handling several cases for h, m, s tokens" ;;
    *)
        echo "seconds case" 
        echo "handling other cases" ;;
esac

References and related questions with examples:

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.