Reputation: 4056
I am trying to add to a script I'm writing a restriction to the input where the user can only input 9 or 10 characters I set it up like this but when I run it, it doesn't work the way I want it to. Everything I type in comes back as 10 characters even if I just put one number. What is wrong with my code?
#!/bin/bash
#
echo "Please input numbers only"
read inputline
if read -n10 inputline
then
echo "10 chars"
else
if read -n9 inputline
then
echo "9 chars"
else
echo "invalid input length"
fi
Upvotes: 1
Views: 1934
Reputation: 360625
Your script is asking for input three times. I'm assuming that the following is closer to what you intend:
#!/bin/bash
read -p "Please input numbers only " inputline
len=${#inputline}
if (( len == 9 || len == 10 ))
then
echo "$len chars"
else
echo "invalid input length"
fi
The -n
option to read
limits the input to the specified number of characters but accepts that length without pressing enter. You can enter fewer by pressing Enter though. I've found it to be useful for -n 1
but rarely otherwise.
Upvotes: 3
Reputation: 140477
Use the offset Parameter Expansion to truncate whatever they enter to a max of 10 chars like so:
$ num="123456789012"; echo ${num::10}
1234567890
Upvotes: 1