[root@vm10 ~]# cat 1.sh#!/bin/bash
echo -n 'Please enter your username: 'read name
echo"Your username is: $name"
[root@vm10 ~]#
[root@vm10 ~]# sh 1.sh
Please enter your username: felix
Your username is: felix
[root@vm10 ~]#
示例2: 从标准输入获取输入,没有赋值给一个变量
[root@vm10 ~]# cat 2.sh#!/bin/bash
echo -n 'Please enter your username: 'readecho"Your username is: $REPLY"
[root@vm10 ~]#
[root@vm10 ~]#
[root@vm10 ~]# sh 2.sh
Please enter your username: felix.zhang
Your username is: felix.zhang
[root@vm10 ~]#
示例3: 使用-p选项指定一个提示符
[root@vm10 ~]# cat 3.sh#!/bin/bash
read -p 'Please enter your username: ' name
echo"Your username is: $name"
[root@vm10 ~]#
[root@vm10 ~]# sh 3.sh
Please enter your username: felix.zhang
Your username is: felix.zhang
[root@vm10 ~]#
[root@vm10 ~]# cat 4.sh#!/bin/bash
ifread -t 5 -p 'Please enter your name: ' name; thenecho"Hello $name"elseechoecho'Timeout'fi
[root@vm10 ~]#
[root@vm10 ~]#
[root@vm10 ~]# sh 4.sh
Please enter your name:
Timeout
[root@vm10 ~]#
[root@vm10 ~]# sh 4.sh
Please enter your name: felix.zhang
Hello felix.zhang
[root@vm10 ~]#
示例5: 使用-s选项,输入数据不回显(不显示在显示器上)
注意:当-s和-p选项一起使用时,-s要放在-p的前面。可以是-sp或者是-s-p
[root@vm10 ~]# cat 5.sh#!/bin/bash
read-s -p 'Please enter your password: ' password
echoecho"Your password is: "$password
[root@vm10 ~]#
[root@vm10 ~]# sh 5.sh
Please enter your password:
Your password is: felix.zhang
[root@vm10 ~]#
示例6: 使用-n选项读取指定数量的字符
采用-n的方式读取n个字符后,不需要用户按回车,read读取到指定数量的字符后就将其传递给变量。
[root@vm10 ~]# cat 6.sh#!/bin/bash
read -n1 -p 'Do you want to continue [y/n]? ' answer
case$answerin
y|Y)
echoecho'You answer is: yes'
;;
n|N)
echoecho'You answer is: no'
;;
*)
echoecho'You answer is invalid'
;;
esac
[root@vm10 ~]#
[root@vm10 ~]# sh 6.sh
Do you want to continue [y/n]? y
You answer is: yes
[root@vm10 ~]# sh 6.sh
Do you want to continue [y/n]? n
You answer is: no
[root@vm10 ~]# sh 6.sh
Do you want to continue [y/n]? a
You answer is invalid
[root@vm10 ~]#