linux command read the content,Linux while 和 read 的用法

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$0scripts.."

ls -l /proc/$mypid/fd

# Close fd # 3 and # 4

exec 3

exec 4>&-

while read 的用法

从标准输入读取

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

从管道读取

$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:$0filename"; exit 1; }

# make sure file exist else die

[ ! -f $FILE] && { echo "Error - File$FILEdoes not exists." ; exit 2; }

# make sure file readonly else die

[ ! -r $FILE] && { echo "Error - Can not read$FILEfile."; exit 3; }

IFS=$(echo -en "\n\b")

exec 3

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

原文:https://www.cnblogs.com/tiantiandas/p/shell_command_read.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值