linux shell實現擷取使用者輸入指定範圍的單個字元的兩種方法

來源:互聯網
上載者:User

方法一:

複製代碼 代碼如下: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 ~]#

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.