赞
踩
read 使用总结
参考链接:https://www.runoob.com/linux/linux-comm-read.html
-a 后面跟一个变量,该变量会被认为是个数组,然后给其赋值,输入时默认是以空格为分割符
-d 后面跟一个标志符,定义一个结束标志,其实只有其后的第一个字符有用,作为结束的标志
-p 后面跟提示信息,即在输入前打印提示信息。
-e 在输入的时候可以使用命令补全功能。
-n 后跟一个数字,定义输入文本的长度,很实用。
-r 屏蔽\,如果没有该选项,则\作为一个转义字符,有的话 \就是个正常的字符了。
-s 安静模式,在输入字符时不再屏幕上显示,例如login时输入密码。
-t 后面跟秒数,定义输入字符的等待时间。
-u 后面跟fd,从文件描述符中读入,该文件描述符可以是exec新开启的。
脚本内容:
#/bin/bash
# 从输入中读取数值,然后赋值给array_name数组
read -a array_name
#打印数组内容
echo ${array_name[@]}
输出:
[root@node1]# sh test
a b c
a b c
脚本内容:
#/bin/bash
#从输入中读取字符串,赋值给变量name,当输入的字符为s时,结束输入
read -d sabc name
echo "name="${name}
输出:
[root@node1]# sh test
tes
name=te
脚本内容:
#/bin/bash
read -p "Please enter a letter:" letter
echo "letter="${letter}
输出:
[root@node1]# sh test
Please enter a letter:apple
letter=apple
# 不加 -e 上下左右键会打印字符
[root@node1]# read
abc^[[A^[[B^[[D^[[C^C
#加 -e 上下左右键可以正常使用,不会打印字符
[root@node1]# read -e
abc
脚本内容:
#/bin/bash
# 限制输入的字符个数只能为5个,输入到第五个以后会结束输入
read -n5 -p "Please enter a letter:" letter
echo "letter="${letter}
输出:
[root@node1]# sh test
Please enter a letter:abcde
letter=abcde
带 -r 脚本内容: #/bin/bash # 输入中的字符串带 \ 时,会正常打印 \ read -r -p "Please enter a letter: " letter echo "letter="${letter} 输出: [root@node1]# sh test Please enter a letter: abc\ndef letter=abc\ndef 不带 -r 脚本内容: #/bin/bash # 输入的字符串带 \, 会当成转义字符,不打印 read -p "Please enter a letter: " letter echo "letter="${letter} 输出: [root@node1]# sh test Please enter a letter: abc\ndef letter=abcndef
脚本内容:
#/bin/bash
# 输入时不显示输入的字符,适用于输入密码
read -s -p "Please enter your password: " passwd
echo "password="${passwd}
输出:
[root@node1]# sh test
Please enter your password:
password=abcd
# -t 指定read 命令输入等待时间,如果 3s 内不输入,会终止输入
[root@node1]# read -t 3 -p "please enter a letter: "
please enter a letter: [root@node1]#
#合并两个文件 脚本内容: #/bin/bash while read -u3 i && read -u4 j do echo $i $j done 3<afile 4<bfile 输出: # sh test.sh 1 a 2 b 3 c # cat afile 1 2 3 4 5 6 # cat bfile a b c
read -u3 i 的意思是从 3 号 fd (file descriptor,文件描述符) 中读一行数据到 i 变量中, 同理你明白 read -u4 j 的意思
而 3<afile 的意思是重定向 afile 到 3 号 fd 中, 4<bfile同理
参考链接:https://zhidao.baidu.com/question/357781350.html
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。