2

How to use bash's "case" statement for "very specific" string patterns (multiple words, including spaces) ?

The problem is: I receive a multi-word String from a function which is pretty specific, including a version number. The version number now changes from time to time. Instead of adding more and more specific string patterns to my case statement, I would like to use a joker (or whatever the word for this is, like "Ubuntu 16.04.? LTS" or "Ubuntu 16.04.* LTS" . However, I didn't find any solution to this yet.

See this shell script I used so far:

    .
    .
    .
    case "${OS}" in
    "SUSE Linux Enterprise Server 11 SP4")
        echo "SLES11 detected."
        ;;
    "Ubuntu 16.04.3 LTS" | "Ubuntu 16.04.4 LTS"     )
        echo "UBUNTU16 detected."
        ;;
    "CentOS Linux 7 (Core)")
        echo "CENTOS7 detected."
        ;;
    *)
        echo "Unknown OS detected. Quitting for safety reasons."
        exit -1
        ;;
    .
    .
    .
2
  • PS: i read the "pattern" part of the manual and tested some variations of "jokers", but it always failed, since i just forgot to simply drop the doublequotes and to escape the whitespaces. duh! Apr 3 '18 at 14:17
  • 1
    I think the term you might be thinking of is "wildcard" (for joker)
    – Jeff Schaller
    Jul 1 '18 at 13:36
2

You can use patterns in case statements, however you can't quote them so you have to escape whitespace.

case ${OS} in
"SUSE Linux Enterprise Server 11 SP4")
    echo "SLES11 detected."
    ;;
Ubuntu\ 16.04.[3-4]\ LTS)
    echo "UBUNTU16 detected."
    ;;
"CentOS Linux 7 (Core)")
    echo "CENTOS7 detected."
    ;;
*)
    echo "Unknown OS detected. Quitting for safety reasons."
    exit -1
    ;;
3
  • @StephenKitt updated.
    – jesse_b
    Apr 3 '18 at 14:08
  • doh!! Escaping the spaces is the solution . sometimes im blind for the easiest solution. thanks. So this did the trick for me: ` Ubuntu\ 16.04.*\ LTS )` Apr 3 '18 at 14:09
  • 5
    You could also quote the literal parts but not the wildcards: 'Ubuntu 16'*) -- I find that to be more readable than backslashes Apr 3 '18 at 14:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.