pherty
pherty

Reputation: 1

How to check if user input is in correct format?

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?

Upvotes: 0

Views: 801

Answers (2)

Oliver Gaida
Oliver Gaida

Reputation: 1920

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
$

Upvotes: 2

tripleee
tripleee

Reputation: 189317

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.

Upvotes: 0

Related Questions