Linux while 和 read 的用法
Posted ZHE
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux while 和 read 的用法相关的知识,希望对你有一定的参考价值。
Reference: linux man doc CSDN roler_ Reads from the file descriptor
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
$read
First Line
$echo $REPLY
First Line
-s : 静默模式
$read -s -p "Input Your Password:" PASSWD
Input Your Password:
$echo $PASSWD
testpass
-a : 读入数据存入数组
$read -a number_array -p "Input number sequence:"
Input number sequence:10 20 50 100
$
$for n in ${number_array[@]}; do echo $n;done
10
20
50
100
-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 file
read -u 3 a b
echo "*** My pid is $$"
mypid=$$
echo "*** Currently open files by $0 scripts.."
ls -l /proc/$mypid/fd
# Close fd # 3 and # 4
exec 3<&-
exec 4>&-
while read 的用法
从标准输入读取
while read line
do
echo $line
done</etc/resolv.conf
# result
; generated by /usr/sbin/dhclient-script
search lvrpf0txgxle3htzsh2w1rj15g.hx.internal.cloudapp.net
nameserver 168.63.129.16
从管道读取
$cat /etc/resolv.conf | while read line;do echo $line;done
# result
; generated by /usr/sbin/dhclient-script
search lvrpf0txgxle3htzsh2w1rj15g.hx.internal.cloudapp.net
nameserver 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<$FILE
while read -u 3 -r line
do
echo $line
done
# Close fd # 3
exec 3<&-
# exit with 0 success status
exit 0
定义分隔符
利用环境变量: IFS 可以定义分隔符
while IFS=: read user _ _ _ _ home shell
do
echo "user: $user. home: $home. shell: $shell"
done</etc/passwd
以上是关于Linux while 和 read 的用法的主要内容,如果未能解决你的问题,请参考以下文章
arm6410,linux,c语言,read函数返回-1,错误:bad address