Search code examples
linuxbashshelldecimalposix

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.

#!/bin/bash

# take input from prompt (-p) and store it in $varweight
read -p 'Enter weight in kg: ' varweight

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

Thank you for your help.


Solution

  • 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

    str="30.4"
    re='^[[:digit:]]{2}\.[[:digit:]]$'
    
    if [[ $str =~ $re ]]; then
        echo 'true'
    fi
    

    On a POSIX compliant shell though you could use case statement

    case $str in  
       [0-9][0-9].[0-9]) echo good ;; 
       *) echo bad;; 
    esac
    

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

    if expr "$str" : '[[:digit:]]\{2\}\.[[:digit:]]$' > /dev/null; then
        echo "true"
    fi