分类: LINUX
2010-11-28 12:44:26
read 命令用法详解
1. 简介
read是一个buildin命令,主要完成对参数的赋值,类似C语言中的scanf。其不仅可以赋值变量,还可以赋值数组;其输入不仅是屏幕,还可以是文件描述符。
2. man中选项说明
-a aname
The words are assigned to sequential indices of the array variable
aname, starting at 0. aname is unset before any new values are
assigned. Other name arguments are ignored.
-d delim
The first character of delim is used to terminate the input line,
rather than newline.
-e If the standard input is coming from a terminal, readline (see READ-
LINE above) is used to obtain the line.
-n nchars
read returns after reading nchars characters rather than waiting for a
complete line of input.
-p prompt
Display prompt on standard error, without a trailing newline, before
attempting to read any input. The prompt is displayed only if input
is coming from a terminal.
-r Backslash does not act as an escape character. The backslash is con-
sidered to be part of the line. In particular, a backslash-newline
pair may not be used as a line continuation.
-s Silent mode. If input is coming from a terminal, characters are not
echoed.
-t timeout
Cause read to time out and return failure if a complete line of input
is not read within timeout seconds. This option has no effect if read
is not reading input from the terminal or a pipe.
-u fd Read input from file descriptor fd.
-a 后跟一个变量,该变量会被认为是个数组,然后给其赋值,默认是以空格为分割符。
-d 后面跟一个标志符,其实只有其后的第一个字符有用,作为结束的标志,会举例说 明。
-p 后面跟提示信息,即在输入前打印提示信息。
-e 在输入的时候可以时候命令补全功能。
-n 后跟一个数字,定义输入文本的长度,很实用。
-r 屏蔽\,如果没有该选项,则\作为一个转义字符,有的话 \就是个正常的字符了。
-s 安静模式,在输入字符时不再屏幕上显示,例如login时输入密码。
-t 后面跟秒数,定义输入字符的等待时间。
-u 后面跟fd,从文件描述符中读入,该文件描述符可以是exec新开启的。
3. 举例
-a举例:
root@localhost:~/test#read -a tao
qq ww ee rr
root@localhost:~/test#echo ${tao[1]}
Ww
-b举例:
root@localhost:~/test#read -d eof -a tao
ww
dd
gg
hh (输入一个e)
root@localhost:~/test#echo ${tao[3]}
Hh
-n举例:
root@localhost:~/test#read -n3 -p "you can input 3 word:"
you can input 3 word:xxx
(输入3个字符后自动退出!)
-s举例:
root@localhost:~/test#read -p password: -s passwd
password:
(这时候输入就不再显示在屏幕上了!)
-e举例:
root@localhost:~/test#read -e file
(tab键补全)
exp1 file ngis_post.sh text
exp5 linux-2.6.27.54/ test xen-3.0.1-install/
-u举例:
root@localhost:~/test#exec 3
root@localhost:~/test#read -u 3 tao
root@localhost:~/test#echo $tao
hello world!
root@localhost:~/test#
注意看下读入的次序:
root@localhost:~/test#cat file
hello world!
i am good
root@localhost:~/test#exec 3
root@localhost:~/test#read -u 3 tao
root@localhost:~/test#echo $tao
hello world!
root@localhost:~/test#read -u 3 tao
root@localhost:~/test#echo $tao
i am good
root@localhost:~/test#
这个选项很有用的,特别是自循环读入的时候。
chinaunix网友2010-11-30 10:59:16
很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com