linux shell实现获取用户输入指定范围的单个字符的两种方法

linux shell实现获取用户输入指定范围的单个字符的两种方法,第1张

linux shell实现获取用户输入指定范围的单个字符的两种方法

方法一:
复制代码 代码如下:
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 "

[root@station1 ~]# cat a.sh

复制代码 代码如下:
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 "

[root@station1 ~]# chmod +x a.sh
[root@station1 ~]# ./a.sh
please input a letter: 123
please input a letter: abc
please input a letter: 4
please input a letter: &
please input a letter: (
please input a letter: a
you input letter a
[root@station1 ~]#

最初使用expr length $letter 替代 wk -v var="$letter" 'BEGIN{print length(var)}'的,但是,当输入*等特殊字符时,会报错。
如下:
[root@station1 ~]# cat data

复制代码 代码如下:
while read -p "please input a letter: " letter
do
((`expr length $letter` == 1)) && expr $letter : [[:alnum:]] > /dev/null && break
done
echo "you input letter $letter "

[root@station1 ~]# bash data
please input a letter: 123
please input a letter: abc
please input a letter: a
you input letter a
[root@station1 ~]# bash data
please input a letter: *
expr: 语法错误
data: line 3: ((: == 1: syntax error: operand expected (error token is "== 1")
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 "

如下:
[root@station1 ~]# cat b.sh

复制代码 代码如下:
while read -p "please input a letter: " letter
do
[[ `echo $letter | awk '/^[[:alpha:]]$/{print "1"}'` -eq 1 ]] && break
done
echo "you input letter $letter "

[root@station1 ~]# chmod +x b.sh
[root@station1 ~]# ./b.sh
please input a letter: *
please input a letter: abc
please input a letter: 234
please input a letter: )
please input a letter: T
you input letter T
[root@station1 ~]#

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/3345978.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-10-06
下一篇 2022-10-06

发表评论

登录后才能评论

评论列表(0条)

保存