0

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" ;;
esac

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

jesse_b
  • 37,005

2 Answers2

0

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
else
  echo "Invalid input, number is expected" >&2
fi

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

jesse_b
  • 37,005
0

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.

doneal24
  • 5,059
  • 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 02 '19 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 02 '19 at 18:33
  • @Jesse_b This can be fixed by adding && exit 0 after the echo – doneal24 May 02 '19 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 02 '19 at 18:36