Shell中read的用法详解

前端之家收集整理的这篇文章主要介绍了Shell中read的用法详解前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

read的常用用法如下:

read -[pstnd] var1 var2 ...

-p提示语句
-n 字符个数
-s 屏蔽回显
-t 等待时间
-d 输入分界

01). read      						# 从标准输入读取一行并赋值给特定变量REPLY
root@linux~# read
Hello,World!
root@linux~# echo $REPLY
Hello,World!

02). read name 						# 从标准输入读取输入并赋值给变量name
root@linux~# read name
Jerry
root@linux~# echo $name
Jerry

03). read var1 var2   				# 第一个变量放置于var1,第二个变量放到var2  
root@linux~# read firstname lastname
Jerry Gao
root@linux~# echo "firstname:$firstname lastname:$lastname"
firstname:Jerry lastname:Gao

04). read -p "text"   				# 打印提示'text',等待输入,并将输入存储在REPLY中
root@linux~# read -p 'Please Enter your name:-->'
Please Enter your name:-->Jerry
root@linux~# echo $REPLY
Jerry

05). read -p "text" var  			# 打印提示'text',等待输入,并将输入存储在VAR中
root@linux~# read -p 'Please Enter your name:-->' name
Please Enter your name:-->Jerry
root@linux~# echo $name
Jerry

06). read -p "text" var1  var2		# 打印提示'text',等待输入,将变量分别存储在var1,var2...
root@linux~# read -p 'What your name? ' firstname lastname
What your name? Jerry Gao
root@linux~# echo "Firstname:$firstname Lastname:$lastname"
Firstname: Jerry Lastname:Gao

07). read -r line 					# 允许输入包含反斜杠
root@linux~# read line          	# 不带-r参数;则反斜杠不显示
This is line 1. \ This is line 2.
root@linux~# echo $line
This is line 1. This is line 2.

root@linux~# read -r line       	# 带-r参数;则反斜杠正常显示显示
This is line 1. \ This is line 2.
root@linux~# echo $line
This is line 1. \ This is line 2.

08). read -t 5						# 指定读取等待时间为5秒
root@linux~# read -t 5 -p 'Your Name:' name
Your Name:Jerry
root@linux~# echo $name       		# 如果5秒还未输入,则不能输入
Jerry

09). read -a arrayname         		# 把单词清单读入arrayname的数组里
root@linux~# read -a citys
BJ SH CD GZ
root@linux~# echo ${citys[*]}
BJ SH CD GZ
root@linux~# echo ${citys[0]}
BJ

10). read -s -p "pwd:" pwd 		# 使用-s参数可以不显示用户的输入
root@linux~# read -p "Enter Your Password:" -s PASSWORD
Enter Your Password:
root@linux~#
root@linux~# echo $PASSWORD			# 刚才输入的密码为:1234
1234


11). read -n 1 -p "Sure?(y/n):"  	# 使用-n,来确定参数个数
root@linux~# read -n 1 -p "Are you sure?(y/n): " ANSWER
Are you sure?(y/n): y              
root@linux~#
root@linux~# echo -e "Your ANSWER is: $ANSWER"
Your ANSWER is: y

12). read -d ":" var				# 使用:作为输入分界符
root@linux~# read -d ";" -p "Enter Your Name:" name
Enter Your Name:Jerry Gao;
root@linux~# echo -e "Your Name: $name"
Your Name: Jerry Gao


read在脚本中的应用:

遍历方式一:

#!/bin/bash

count=0

while read line
do
    echo -e "$count:-->$line"
    count=$[ count + 1]
done < /etc/passwd

遍历方式二:

#!/bin/bash

awk -F: '{print $1,$7}' /etc/passwd | while read user bash
do
    echo -e "USER=$user; BASH=$bash"
done
原文链接:https://www.f2er.com/bash/391325.html

猜你在找的Bash相关文章