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

出处:www.l1mn.com

原文标题:linux shell获取用户输入

原文地址:https://www.l1mn.com/p/1xpve3.html

本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。

分类:linuxshell
标签:shell
评论

皖ICP备2023023451号

Copyright © L1MN.COM 联系方式:l1mnfw@163.com