2011-01-21 89 views
1

我想添加到脚本我正在写输入的限制,用户只能输入9或10个字符我这样设置,但是当我运行它时,它不按我想要的方式工作。即使我只输入一个数字,我输入的所有内容都会返回10个字符。我的代码有什么问题?允许读只接受两种长度

#!/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 

回答

3

你的脚本是要求输入三次。我假设以下是更接近你想要什么:

#!/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 

-n选项read限制了输入到指定的字符数,但承认,长度不按进入。您可以通过按Enter键输入更少。我发现它对-n 1有用,但很少有其他用途。

+1

+1,但不要忘记`y`后面的空格。 – SiegeX 2011-01-21 21:26:36

1

使用偏移参数扩展截断无论他们进入到10个字符一个最大像这样:

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