Skip to content
Advertisement

Only accept 4 character long, decimal numbers as user input for read

I am writing a small script to easily capture weights, which are taken from user input with read -p.

I want all captured weights to be 4 characters long, decimal numbers in the format XX.X. For example 30.2 kg.

JavaScript

How can I make sure users can only input decimal numbers in that format?

Thank you for your help.

Advertisement

Answer

One way would be to use a regex and assert the length to remove false positives (optionally). Of course the below would require the bash shell because the ~ is not POSIX compliant

JavaScript

On a POSIX compliant shell though you could use case statement

JavaScript

A much better POSIX compliant tool would be to use expr to do the regex match.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement