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

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

2 Answers 2

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.

4
  • This would still execute echo $amount >>manual-entry no matter what the input is. That may not be what OP is looking for Commented May 2, 2019 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. Commented May 2, 2019 at 18:33
  • @Jesse_b This can be fixed by adding && exit 0 after the echo Commented May 2, 2019 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. Commented May 2, 2019 at 18:36
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.