linux shell 获取用户名,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

总结

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值