Linux常用命令-read

命令

read

描述

Read a line from the standard input and split it into fields
按行读取输入的内容

用法

1
read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]

选项

1
2
3
4
5
6
7
8
9
10
Options:
-a array 定义一个数组,所输入的内容将作为该数组的元素,默认以空格分割元素
-d delim 定义一个结束符,当输入该字符时,自动结束当前输入
-e 支持tab键补全文件名或路径
-n nchars 定义输入的字符长度,达到定义的长度后自动结束;如果输入的内容小于定义长度且按下回车键则也会结束
-N nchars 严格定义输入的字符长度,即使按下回车键也仅表示增加一个字符,并不会结束
-p prompt 定义提示信息
-r 不转义反斜杠,即将反斜杠也作为一个字符
-s 静默模式,不显示输入的内容
-t timeout 定义超时时间,如果到达超时时间仍未输入完成,则会自动退出且不读取任何输入的内容

注意

部分选项不支持合并,建议拆分开,如read -t 5 -p "input something: " name

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
1. 定义一个数组info
$ read -a info
zhangsan beijing 123
$ echo $info
zhangsan
$ echo ${info}
zhangsan
# 显示数组中的第2个元素
$ echo ${info[1]}
beijing
$ echo ${info[*]}
zhangsan beijing 123
# 显示数组中元素的个数
$ echo ${#info[*]}
3

# 给多个变量赋值
$ read a b c
1 2 3
$ echo $a
1
$ echo $b
2
$ echo $c
3

2. 定义一个结束符z
$ read -d z info
ab
cdef
sjdfo123
z
$ echo $info
ab cdef sjdfo123
# 按照输入的格式显示
$ echo "$info"
ab
cdef
sjdfo123

3. 定义输入的字符长度
$ read -n 3 a
abc
# -n 回车表示结束输入
$ read -n 3 a
a
# -N 回车表示一个普通字符
$ read -N 3 a
a
b
$ echo $a
a b
$ echo "$a"
a
b

4. 定义提示信息
$ read -p "input your name: " name
input your name: usera
$ echo $name
usera

5. 不显示输入的内容,例如设置密码不回显
$ read -s -p "input your password: " passwd
input your password:
$ echo $passwd
abc

6. 定义超时时间
$ read -t 5 -p "choose yes or no: " choose
choose yes or no:
$ echo $choose

$ read -t 5 -p "choose yes or no: " choose
choose yes or no: yes
$ echo $choose
yes