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


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

    1. $ cat askpassword.sh 
    2. #!/bin/bash 
    3. # Hiding input data 
    4. read -s -p "Enter your password: " pass 
    5. echo 
    6. echo "Your password is $pass" 
    7. exit 
    8. $ ./askpassword.sh 
    9. Enter your password: 
    10. Your password is Day31Bright-Test 
    11. $


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

    1. $ cat readfile.sh 
    2. #!/bin/bash 
    3. # Using the read command to read a file 
    4. count=1 
    5. cat $HOME/scripts/test.txt | while read line 
    6. do 
    7.     echo "Line $count: $line" 
    8.     count=$[ $count + 1
    9. done 
    10. echo "Finished processing the file." 
    11. exit 
    12. $ cat $HOME/scripts/test.txt 
    13. The quick brown dog jumps over the lazy fox. 
    14. This is a test. This is only a test
    15. O Romeo, Romeo! Wherefore art thou Romeo? 
    16. $ ./readfile.sh 
    17. Line 1: The quick brown dog jumps over the lazy fox. 
    18. Line 2: This is a test. This is only a test
    19. Line 3: O Romeo, Romeo! Wherefore art thou Romeo? 
    20. Finished processing the file


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

  • 相关阅读:
    【MySQL】深入理解MySQL索引原理(MySQL专栏启动)
    基于Matlab使用线性FM波形对带状合成孔径雷达系统建模(附源码)
    咳嗽检测深度神经网络算法
    网络与VPC之动手实验
    WebGL 用鼠标控制物体旋转
    并发编程——LockSupport工具和Condition接口
    华为H12-831题库
    家政预约小程序07服务分类展示
    [autojs]界面上检测无障碍服务和悬浮窗
    汪汪熊の模板
  • 原文地址:https://blog.csdn.net/mmmmm168m/article/details/134047500