shell 读取输入,shell 无法获取文件的状态
终极管理员 知识笔记 132阅读
无显示读取
有时你需要从脚本用户处得到输入但又不想在屏幕上显示输入信息。典型的例子就是输入密码但除此之外还有很多种需要隐藏的数据。
-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 # count1 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退出状态码退出。

标签: