0

I am attempting to write a bash script that takes input from the keyboard and displays text depending on what number was entered:

#!/bin/bash
read -p "Enter your age: " AGE
case $AGE in
        [1-12]*)
                echo "You are just a child." ;;
        [13-19]*)
                echo "You are just a teenager." ;;
        [20-29]*)
                echo "You are a young adult." ;;
        [30-39]*)
                echo "You are a moderate age adult." ;;
               *)
                echo "You are really old."
esac

When you enter numbers like 3 or 4, it doesn't fall in the first range. It falls withing the 30-39 and the default.

Where am I messing up?

  • Square braces [20-29]* form regular expressions to denote character ranges, not number ranges. So you may write [0-5] to mean the digits 0,1,2,3,4,5. But [20-29] is interpreted as the digit 2, the digits 0-2 (which overlaps in the digit 2) and the digit 9. The asterix allows multiple such digits in series. – user unknown Feb 22 '23 at 15:39
  • 1
    @userunknown, case statements in the shell use shell patterns, not regexes. The brackets are similar, but the asterisk means "any amount of any characters" (and not "any amount of the previous atom"). – ilkkachu Feb 22 '23 at 15:41
  • @ilkkachu: +1 for the correction on the asterix. But "regular expression" isn't a reserved word. Any syntax which allows to decribe the rules of how to build an expression according to rules is a regular expression, isn't it? – user unknown Feb 23 '23 at 13:27
  • @userunknown, welll, it's a rather generic phrase, I'll grant you that, but... The phrase comes from language theory, from regular languages, which most people in IT don't need to care about (and you can ask the theorists what's so "regular" in them). More importantly, "regular expressions" or regexes have come to mean a particular sort of pattern matching syntax. Or rather, a family of such. – ilkkachu Feb 23 '23 at 13:32
  • In common use, the pattern matching language of the shell is sufficiently different that the patterns aren't called "regular expressions". The differences between the regex dialects are a bit of a nuisance already, but I think the regex vs. shell pattern distinction is important to note exactly because both are common in CLI use. Common, but different. Shell wildcards (ls -l *.txt) take shell patterns, grep takes regexes. AWK uses (extended) regexes, find -name takes patterns. And the syntaxes are different, so mistaking one for the other will just make it not work. – ilkkachu Feb 23 '23 at 13:35

0 Answers0