linux shell獲取用戶輸入


一、獲取用戶輸入
1、基本讀取
read命令接收標准輸入的輸入,或其它文件描述符的輸入。得到輸入后,read命令將數據輸入放入一個標准變量中。
[root@rac2 ~]# cat t8.sh
#!/bin/bash
#testing the read command
echo -n "enter your name:" ---:-n用於允許用戶在字符串后面立即輸入數據,而不是在下一行輸入。
read name
echo "hello $name ,welcome to my program."
[root@rac2 ~]# ./t8.sh
enter your name:zhou
hello zhou ,welcome to my program.
read命令的-p選項,允許在read命令行中直接指定一個提示:
[root@rac2 ~]# cat t9.sh
#!/bin/bash
#testing the read -p option
read -p "please enter your age:" age ---age與前面必須有空格
echo "your age is $age"
[root@rac2 ~]# ./t9.sh
please enter your age:10
your age is 10
2、在read命令中也可以不指定變量,如果不指定變量,那么read命令會將接收到的數據防止在環境變量REPLAY中
[root@rac2 ~]# cat t10.sh
#!/bin/bash
#tesing the replay environment variable
read -p "enter a number:"
factorial=1
for (( count=1; count<=$REPLY; count++ ))
do
factorial=$[ $factorial * $count ]
done
echo "the factorial of $REPLY is $factorial"
[root@rac2 ~]# ./t10.sh
enter a number:5
the factorial of 5 is 120
3、計時
-t選項指定read命令等待輸入的秒數。當計時器計時數滿時,read命令返回一個非零退出狀態
[root@rac2 ~]# cat t11.sh
#!/bin/bash
#timing the data entry
if read -t 5 -p "please enter your name:" name
then
echo "hello $name ,welcome to my script"
else
echo "sorry ,tow slow!"
fi
[root@rac2 ~]# ./t11.sh
please enter your name:zhou
hello zhou ,welcome to my script
[root@rac2 ~]# ./t11.sh
please enter your name:sorry ,tow slow!
4、默讀
有時候需要腳本用戶進行輸入,但不希望輸入的數據顯示在監視器上,(實際上是顯示的只是read命令將文本顏色設置為與背景相同的了)。
[root@rac2 ~]# cat t12.sh
#!/bin/bash
#hiding input data from the monitor
read -s -p "enter your password:" pass
echo "is your password really $pass?"
[root@rac2 ~]# ./t12.sh
enter your password:is your password really 12345?
5、讀取文件
每調用一次read命令都會讀取文件中的一行文本,當文件中沒有可讀的行時,read命令將以非零退出狀態退出。
[root@rac2 ~]# cat t13.sh
#!/bin/bash
count=1
cat test | while read line
do
echo "line $count:$line"
count=$[$count + 1]
done
[root@rac2 ~]# ./t13.sh
line 1:zhou
line 2:xiao
line 3:zhou


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM