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?

2 Answers 2

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
$
Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

Can i ask what this do: [!,0-9] | ,,, )
Added an explanation, and a case I forgot to test for earlier.
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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.