添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
含蓄的火锅  ·  Java 8 上的 SQL Server ...·  2 周前    · 
深情的鞭炮  ·  Install .NET Runtime ...·  2 周前    · 
小胡子的大葱  ·  Gentoo Forums :: View ...·  1 周前    · 
爽快的绿豆  ·  linux kill命令__linux ...·  1 周前    · 
追风的机器猫  ·  Json 转实体·  2 周前    · 
谦逊的苦瓜  ·  GitHub - ...·  3 月前    · 
Hello Rich Blum, welcome to my program.

echo命令使用了-n选项,该选项不会在字符串末尾输出换行符,允许脚本用户紧跟其后输入数据,而不是下一行。 read命令包含了-p选项,允许用户直接在read命令行指定提示符

$ cat test22.sh
#!/bin/bash
# testing the read -p option
read -p "Please enter your age: " age
days=$[ $age * 365 ]
echo "That makes you over $days days old! "
$ ./test22.sh
Please enter your age: 10
That makes you over 3650 days old!

read命令会将提示符后输入的所有数据分配给单个变量,要么指定多个变量,输入的每个数据值都会分配给变量列表中的下一个变量,如果变量数量不够,剩下的数据就全部分配给最后一个变量。

$ cat test23.sh
#!/bin/bash
# entering multiple variables
read -p "Enter your name: " first last
echo "Checking data for $last, $first…"
$ ./test23.sh
Enter your name: Rich Blum
Checking data for Blum, Rich...

也可以在read命令行中不指定变量,此时read会将它收到的任何数据存入环境变量REPLY中

$ cat test24.sh
#!/bin/bash
# Testing the REPLY Environment variable
read -p "Enter your name: "
echo Hello $REPLY, welcome to my program.
$ ./test24.sh
Enter your name: Christine
Hello Christine, welcome to my program.

使用read命令时脚本很可能会一直等着用户输入,此时可以设置一个计时器来让脚本在超过输入时间后继续执行

$ cat test25.sh
#!/bin/bash
# timing the data entry
if read -t 5 -p "Please enter your name: " name
echo "Hello $name, welcome to my script"
echo "Sorry, too slow! "
$ ./test25.sh
Please enter your name: Rich
Hello Rich, welcome to my script
$ ./test25.sh
Please enter your name:
Sorry, too slow!

也可以不对输入过程计时,而是让read命令来统计输入的字符数,当输入的字符数达到预设的字符数时,就会自动退出,将输入的数据赋值给变量

$ cat test26.sh
#!/bin/bash
# getting just one character of input
read -n1 -p "Do you want to continue [Y/N]? " answer
case $answer in
Y | y) echo
echo "fine, continue on…";;
N | n) echo
echo OK, goodbye
exit;;
echo "This is the end of the script"
$ ./test26.sh
Do you want to continue [Y/N]? Y
fine, continue on…
This is the end of the script
$ ./test26.sh
Do you want to continue [Y/N]? n
OK, goodbye

将-n选项与值1一起使用,告诉read命令在接受单个字符后退出。

隐藏方式读取

-s选项可以避免在read命令中输入的数据出现在显示器上

$ cat test27.sh
#!/bin/bash
# hiding input data from the monitor
read -s -p "Enter your password: " pass
echo "Is your password really $pass? "
$ ./test27.sh
Enter your password:
Is your password really T3st1ng?

文件中读取

read可以用来直接读取文件里保存的数据,每次调用read命令,它都会从文件中读取一行,当文件中没有内容后,read退出

$ cat test28.sh
#!/bin/bash
# reading data from a file
count=1
cat test | while read line
echo "Line $count: $line"
count=$[ $count + 1]
echo "Finished processing the file"
$ cat test
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?
$ ./test28.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