开发者

Allow read to only accept two lengths

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


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.


Use the offset Parameter Expansion to truncate whatever they enter to a max of 10 chars like so:

$ num="123456789012"; echo ${num::10}
1234567890
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜