This question already has an answer here:

I have shell script for data entry. Same is made for various data entry which creates file and further for statement generation.i have a part as below where i want to ensure that entered value must be number e.g.130,1300,13500 or any thing but only number.currently i am doing this:

echo -e "Enter loan amount :\c"
read amount
case $amount in
[0-9]) echo $amount >>manual-entry ;;
*)echo " Entered value is not number" ;;

This allowed only one number to enter. My enter value can 1 to 99999999999 anything. How can i fix this

marked as duplicate by Kusalananda shell-script May 2 at 18:36

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    Should your script allow floating point numbers? (numbers with decimals) – Jesse_b May 2 at 18:05
  • 2
    negative numbers? hex numbers? scientific notation? – Jeff Schaller May 2 at 18:19
  • Yes may with decimal,no hex,scitific nos – Kalpesh Bhoj May 3 at 2:51

Possibly something like this

typeset -i amount
read -rp 'Enter loan amount: ' amount
[[ "$amount" == 0 ]] && echo "enter a positive integer"
echo $amount >>manual-entry

This will produce an error on entering a floating point number. Entering a string will set amount to 0.

  • This would still execute echo $amount >>manual-entry no matter what the input is. That may not be what OP is looking for – Jesse_b May 2 at 18:20
  • indeed, I'd rewrite as if [[ "$amount" -gt 0 ]]; then echo "$amount" >> manual-entry; else echo "Echo a positive integer"; fi, or possibly use an until loop rather than a single if/then test. – DopeGhoti May 2 at 18:33
  • @Jesse_b This can be fixed by adding && exit 0 after the echo – doneal24 May 2 at 18:34
  • @DougO'Neal: In this case it's likely fine but it's generally bad practice to chain more than one && or || in a single list. I would recommend an if construct as DopeGhoti suggested. – Jesse_b May 2 at 18:36

You can use a shell test to perform an integer comparison against itself:

read -rp 'Enter loan amount: ' amount
if [ "${amount:-0}" -eq "${amount:-1}" 2>/dev/null ]; then
  echo "$amount" >> manual-entry
  echo "Invalid input, number is expected" >&2

We are comparing ${amount:-0} to ${amount:-1} to ensure this will still fail on null input. Otherwise the -eq operator will error for a non-integer comparison. If the input is an integer it will pass.

Note: this will not support floating point

Not the answer you're looking for? Browse other questions tagged or ask your own question.