shell_51.Linux获取用户输入_无显示读取,从文件中读取

无显示读取
有时你需要从脚本用户处得到输入,但又不想在屏幕上显示输入信息。典型的例子就是输入密码,但除此之外还有很多种需要隐藏的数据。
-s 选项可以避免在 read 命令中输入的数据出现在屏幕上(其实数据还是会被显示,只不过 read 命令将文本颜色设成了跟背景色一样)。
来看一个在脚本中使用-s 选项的例子:

$ cat askpassword.sh 
#!/bin/bash 
# Hiding input data 
# 
read -s -p "Enter your password: " pass 
echo 
echo "Your password is $pass" 
exit 
$ 
$ ./askpassword.sh 
Enter your password: 
Your password is Day31Bright-Test 
$


从文件中读取
我们也可以使用 read 命令读取文件。每次调用 read 命令都会从指定文件中读取一行文本。
当文件中没有内容可读时,read 命令会退出并返回非 0 退出状态码。
其中麻烦的地方是将文件数据传给 read 命令。最常见的方法是对文件使用 cat 命令,将结果通过管道直接传给含有 read 命令的 while 命令。
来看下面的例子:

$ cat readfile.sh 
#!/bin/bash 
# Using the read command to read a file 
# 
count=1 
cat $HOME/scripts/test.txt | while read line 
do 
    echo "Line $count: $line" 
    count=$[ $count + 1 ] 
done 
echo "Finished processing the file." 
exit 
$ 
$ cat $HOME/scripts/test.txt 
The quick brown dog jumps over the lazy fox. 
This is a test. This is only a test. 
O Romeo, Romeo! Wherefore art thou Romeo? 
$ 
$ ./readfile.sh 
Line 1: The quick brown dog jumps over the lazy fox. 
Line 2: This is a test. This is only a test. 
Line 3: O Romeo, Romeo! Wherefore art thou Romeo? 
Finished processing the file. 
$ 


while 循环会持续通过 read 命令处理文件中的各行,直到 read 命令以非 0退出状态码退出。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微辣已是极限

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值