Shell中read的用法详解

来源:互联网 发布:附近编程培训班 编辑:程序博客网 时间:2024/05/21 03:55

read的常用用法如下:

read -[pstnd] var1 var2 ...

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

01). read      # 从标准输入读取一行并赋值给特定变量REPLYroot@linux~# readHello,World!root@linux~# echo $REPLYHello,World!02). read name # 从标准输入读取输入并赋值给变量nameroot@linux~# read nameJerryroot@linux~# echo $nameJerry03). read var1 var2   # 第一个变量放置于var1,第二个变量放到var2  root@linux~# read firstname lastnameJerry Gaoroot@linux~# echo "firstname:$firstname lastname:$lastname"firstname:Jerry lastname:Gao04). read -p "text"   # 打印提示'text',等待输入,并将输入存储在REPLY中root@linux~# read -p 'Please Enter your name:-->'Please Enter your name:-->Jerryroot@linux~# echo $REPLYJerry05). read -p "text" var  # 打印提示'text',等待输入,并将输入存储在VAR中root@linux~# read -p 'Please Enter your name:-->' namePlease Enter your name:-->Jerryroot@linux~# echo $nameJerry06). read -p "text" var1  var2# 打印提示'text',等待输入,将变量分别存储在var1,var2...root@linux~# read -p 'What your name? ' firstname lastnameWhat your name? Jerry Gaoroot@linux~# echo "Firstname:$firstname Lastname:$lastname"Firstname: Jerry Lastname:Gao07). read -r line # 允许输入包含反斜杠root@linux~# read line          # 不带-r参数;则反斜杠不显示This is line 1. \ This is line 2.root@linux~# echo $lineThis is line 1. This is line 2.root@linux~# read -r line       # 带-r参数;则反斜杠正常显示显示This is line 1. \ This is line 2.root@linux~# echo $lineThis is line 1. \ This is line 2.08). read -t 5# 指定读取等待时间为5秒root@linux~# read -t 5 -p 'Your Name:' nameYour Name:Jerryroot@linux~# echo $name       # 如果5秒还未输入,则不能输入Jerry09). read -a arrayname         # 把单词清单读入arrayname的数组里root@linux~# read -a citysBJ SH CD GZroot@linux~# echo ${citys[*]}BJ SH CD GZroot@linux~# echo ${citys[0]}BJ10). read -s -p "pwd:" pwd # 使用-s参数可以不显示用户的输入root@linux~# read -p "Enter Your Password:" -s PASSWORDEnter Your Password:root@linux~#root@linux~# echo $PASSWORD# 刚才输入的密码为:1234123411). read -n 1 -p "Sure?(y/n):"  # 使用-n,来确定参数个数root@linux~# read -n 1 -p "Are you sure?(y/n): " ANSWERAre you sure?(y/n): y              root@linux~#root@linux~# echo -e "Your ANSWER is: $ANSWER"Your ANSWER is: y12). read -d ":" var# 使用:作为输入分界符root@linux~# read -d ";" -p "Enter Your Name:" nameEnter Your Name:Jerry Gao;root@linux~# echo -e "Your Name: $name"Your Name: Jerry Gao


read在脚本中的应用:

遍历方式一:

#!/bin/bashcount=0while read linedo    echo -e "$count:-->$line"    count=$[ count + 1]done < /etc/passwd

遍历方式二:

#!/bin/bashawk -F: '{print $1,$7}' /etc/passwd | while read user bashdo    echo -e "USER=$user; BASH=$bash"done


原创粉丝点击