0

In a case statement like this:

case $foo in
        bar)
            echo "the value of foo is bar"
            ;;
        *)
            echo "the value of foo is not bar"
            ;;
esac    

why is there an in after case $foo? Wouldn't a syntax that dispensed with it be just as good or better? What does it mean?

1
  • It doesn't mean anything. It's just required by the syntax. And yes, there are an infinite number of possible syntaxes which could dispense with, but none of them is the syntax of the shell language.
    – user313992
    Apr 16, 2020 at 12:23

1 Answer 1

1

It's required by the syntax.

Semantically it introduces a set of one or more globs (expressions) for the case statement, against each of which the case variable is compared.

Note that you should be quoting $foo when you use it, i.e.

case "$foo" in ... esac
8
  • but why is the syntax like that, why isn't the in dispensed with?
    – Toothrot
    Apr 15, 2020 at 20:09
  • 1
    surely whoever invented the language had a reason for making that choice, and surely there are many who can make an educated guess as to what that reason was
    – Toothrot
    Apr 15, 2020 at 20:16
  • 2
    "case item in { value, value, value }" is more readable perhaps than "case item { value, value, value }"? Apr 15, 2020 at 20:19
  • 2
    Also, it (kinda) follows the same pattern as the for loop: for var in list; do ...; done. So that's case $var in (case1) ... ;; (case2) ... ;; (case3) ... ;; esac.
    – Kusalananda
    Apr 15, 2020 at 20:22
  • 1
    No, you should not be quoting in that case. Quoting it makes no difference.
    – user313992
    Apr 16, 2020 at 12:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .