0

How can I check if user input is in correct format?

My script:

#!/bin/bash
echo 'Enter 3 numbers separated by comma'
read text
#here i want to check if user input is in correct format

I want user input look like this: 1,2,3.

But when user input will look e.g like this: 123 or: 1.2.3 an error text message will pop up.

Maybe I have to use arguments but I don't know how?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
pherty
  • 1
  • 2

2 Answers2

2

see man bash, you can test a variable with regular expressions:

[[ $text =~ ^[0-9]+,[0-9]+,[0-9]+$ ]] || echo wrong format

Example:

$ text=1,a,4
$ [[ $text =~ ^[0-9]+,[0-9]+,[0-9]+$ ]] || echo wrong format
wrong format
$ text=1,12,34
$ [[ $text =~ ^[0-9]+,[0-9]+,[0-9]+$ ]] || echo wrong format
$
Oliver Gaida
  • 1,722
  • 7
  • 14
0

You can compare the input string to a pattern.

#!/bin/bash
while true; do
    read -p 'Enter 3 numbers separated by comma' -r text
    case $text in
     *[!,0-9]* | *,*,*,* | ,*,* | *,*, ) ;;
     *,*,* ) break;;
    esac
    echo invalid
done

Your processing will be much easier if you require whitespace instead of commas between the values, though.

#!/bin/bash
while true; do
    read -p 'Enter 3 numbers separated by space' -r first second third
    case $first,$second,$third in
     *[!,0-9]* | *,*,*,* | ,*,* | *,*, ) ;;
     *,*,* ) break;;
    esac
    echo invalid
done

In brief, each expression between | up to ) is examined like a glob pattern (what you use for file name wildcards, like *.png or ?.txt); the subpattern [!abc] matches a single character which is not a, b, or c; these consecutive characters can also be expressed as a range [!a-c].

So, we reject anything which contains a character which isn't a number or a comma, anything with too many commas, anything with commas at the edges, and (implicitly, by falling through) anything with too few commas.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 1
    Can i ask what this do: *[!,0-9]* | *,*,*,* ) – pherty Oct 24 '20 at 19:47
  • Added an explanation, and a case I forgot to test for earlier. – tripleee Oct 24 '20 at 19:52
  • Maybe is it possible to check it like this? But i got error in console. `if [$text =~ *,*,*] then echo 'correct' else echo 'not correct' fi` – pherty Oct 24 '20 at 20:07
  • You're not checking if the items are numbers; you can't really do that in a single check with just glob patterns. Also the `[ ... ]` syntax requires spaces inside the brackets. – tripleee Oct 24 '20 at 20:13