Chinaunix首页 | 论坛 | 博客
  • 博客访问: 915370
  • 博文数量: 75
  • 博客积分: 1216
  • 博客等级: 少尉
  • 技术积分: 1998
  • 用 户 组: 普通用户
  • 注册时间: 2012-08-11 16:20
个人简介

优秀是一种习惯

文章分类

全部博文(75)

文章存档

2014年(1)

2013年(29)

2012年(45)

分类: Python/Ruby

2012-09-19 20:24:17

如下需求:
要求获取用户输一个字符a-zA-Z:
方法一:

echo `echo {a..z}``echo {A..Z}` > /tmp/letterfile
while read -p "please input a letter: " letter
do
        ((`awk -v var="$letter" 'BEGIN{print length(var)}'` == 1)) && grep -q $letter /tmp/tmpfile && break
done
rm -f /tmp/letterfile
echo "you input letter $letter "


  1. [root@station1 ~]# cat a.sh
  2. echo `echo {a..z}``echo {A..Z}` > /tmp/letterfile
  3. while read -p "please input a letter: " letter
  4. do
  5. ((`awk -v var="$letter" 'BEGIN{print length(var)}'` == 1)) && grep -q $letter /tmp/tmpfile && break
  6. done
  7. rm -f /tmp/letterfile
  8. echo "you input letter $letter "
  9. [root@station1 ~]# chmod +x a.sh
  10. [root@station1 ~]# ./a.sh
  11. please input a letter: 123
  12. please input a letter: abc
  13. please input a letter: 4
  14. please input a letter: &
  15. please input a letter: (
  16. please input a letter: a
  17. you input letter a
  18. [root@station1 ~]#
我已开始是使用expr length $letter 替代wk -v var="$letter" 'BEGIN{print length(var)}'的但是,当你输入*等特殊字符时,会报错。如下:


  1. [root@station1 ~]# cat data
  2. while read -p "please input a letter: " letter
  3. do
  4. ((`expr length $letter` == 1)) && expr $letter : [[:alnum:]] > /dev/null && break
  5. done
  6. echo "you input letter $letter "
  7. [root@station1 ~]# bash data
  8. please input a letter: 123
  9. please input a letter: abc
  10. please input a letter: a
  11. you input letter a
  12. [root@station1 ~]# bash data
  13. please input a letter: *
  14. expr: 语法错误
  15. data: line 3: ((: == 1: syntax error: operand expected (error token is "== 1")
  16. please input a letter:


方法二:
while read -p "please input a letter: " letter
do
    [[ `echo $letter | awk '/^[[:alpha:]]$/{print "1"}'` -eq 1 ]] && break
done
echo "you input letter $letter "

如下:

  1. [root@station1 ~]# cat b.sh
  2. while read -p "please input a letter: " letter
  3. do
  4. [[ `echo $letter | awk '/^[[:alpha:]]$/{print "1"}'` -eq 1 ]] && break
  5. done
  6. echo "you input letter $letter "
  7. [root@station1 ~]# chmod +x b.sh
  8. [root@station1 ~]# ./b.sh
  9. please input a letter: *
  10. please input a letter: abc
  11. please input a letter: 234
  12. please input a letter: )
  13. please input a letter: T
  14. you input letter T
  15. [root@station1 ~]#


阅读(4897) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~