Reference:
read 命令说明
SYNTAX : read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
OPTIONS :
-r : 忽视转义符
-s : 静默模式. 对于 [ 输入密码 ] 的需求.
-a ARRAY_NAME : 将输入的字符存入数组.
-d : 用 -d 参数值的第一个字符定义结束符. 默认为换行符.
-n NUMBER: 输入 -n 参数值定义的字符个数时, 自动结束. 当使用 Enter 时, 结束交互.
-N NUMBER : 输入 -N 指定参数的字符个数时, 自动结束. 当使用 Enter 的时候, 不结束交互.
-p CONTENT : 交互时的提示信息
-t NUMBER: 超时时间, 单位 : 秒 (s)
-u FD: 从文件描述符中获取输入
EXAMPLES
read 如果不指定变量名称, 则输入的值默认赋给: REPLY
$readFirst Line$echo $REPLYFirst Line
-s : 静默模式
$read -s -p "Input Your Password:" PASSWDInput Your Password:$echo $PASSWDtestpass
-a : 读入数据存入数组
$read -a number_array -p "Input number sequence:"Input number sequence:10 20 50 100$$for n in ${number_array[@]}; do echo $n;done102050100
-u : 从文件描述符读入数据
#!/bin/bash# Let us assign the file descriptor to file for input fd # 3 is Input file exec 3< /etc/resolv.conf# Let us assign the file descriptor to file for output fd # 3 is Input file exec 4> /tmp/output.txt # Use read command to read first line of the fileread -u 3 a becho "*** My pid is $$"mypid=$$echo "*** Currently open files by $0 scripts.."ls -l /proc/$mypid/fd# Close fd # 3 and # 4exec 3<&-exec 4>&-
while read 的用法
从标准输入读取
while read linedo echo $linedone
从管道读取
$cat /etc/resolv.conf | while read line;do echo $line;done# result; generated by /usr/sbin/dhclient-scriptsearch lvrpf0txgxle3htzsh2w1rj15g.hx.internal.cloudapp.netnameserver 168.63.129.16
从文件描述符读取
#!/bin/bash# Shell script utility to read a file line line.FILE="$1"# make sure filename supplied at a shell prompt else die[ $# -eq 0 ] && { echo "Usage: $0 filename"; exit 1; } # make sure file exist else die[ ! -f $FILE ] && { echo "Error - File $FILE does not exists." ; exit 2; }# make sure file readonly else die[ ! -r $FILE ] && { echo "Error - Can not read $FILE file."; exit 3; }IFS=$(echo -en "\n\b")exec 3<$FILEwhile read -u 3 -r linedo echo $linedone# Close fd # 3exec 3<&-# exit with 0 success status exit 0
定义分隔符
利用环境变量: IFS 可以定义分隔符
while IFS=: read user _ _ _ _ home shelldo echo "user: $user. home: $home. shell: $shell"done