Linux read命令

介绍

read命令是一个非常重要的bash命令,用于从键盘或者表中输入中文本,并且可以和用户进行交互;该命令可以一次读取多个变量的值,变量和输入的值都需要使用空格隔开。在read命令后面,如果没有指定变量名,读取的数据将被自动赋值给特定的变量REPLY,read的参数比较少使用的比较多的几个参数包括:-a(用于数组),-p(给出输入的提示符),-t(指定读取值时等待的时间单位是秒),-s(不显示输入的值,一般用于密码的输入);当然read也可以不使用参数。

1.不使用参数

[root@localhost bash]# read name
chen
[root@localhost bash]# echo $name
chen

2.读取多个变量,变量之间要使用空格隔开,输入的值也要空格对应。

[root@localhost bash]# read a b c
1 2 3
[root@localhost bash]# echo "a=$a b=$b c=$c"
a=1 b=2 c=3

3.-a参数,使用-a参数那么就相当于定义了一个数组变量,输入的如果是多个值那么需要使用空格隔开,使用数组时一定不要忘记“{}”大括号。

[root@localhost bash]# read -a fruit
apple banana orange
[root@localhost bash]# echo "all fruit is ${fruit[0]} ${fruit[1]} ${fruit[2]}"
all fruit is apple banana orange

4.-p参数,给出输入的提示,在输入的时候给与指定的信息提示,并将输入的信息赋值给var。

[root@localhost bash]# read -p "enter everything:" var
enter everything:new
[root@localhost bash]# echo $var
new

5.-s参数,不显示输入的信息,通常用于密码的输入

read -p "enter your password:" -s pwd
enter your password:
[root@localhost bash]# echo $pwd
123

6.-t参数,指定等待用户输入的时间,如果在指定的时间内没有输入信息那么就结束输入

[root@localhost bash]# read -t 30 new
abc
[root@localhost bash]# echo $new
abc

7.-r参数,允许输入的值中包含反斜杠“”,反斜杠也作为值输出

[root@localhost bash]# read -r abc
a
[root@localhost bash]# echo $abc
a

8.-d参数,以指定的字符作为命令的结束输入,在未输入指定的结束符之前输入窗口一直存在按enter键也没用,下面的例子中是使用分号作为结束输入的符合也可以使用其它符合。

[root@localhost bash]# read -d ";" bb
1122
1111
;[root@localhost bash]# echo $bb
1122 1111

9.-n参数,读取指定的个字符给变量,当你输入完指定给字符之后命令会自动终止。

[root@localhost bash]# read -n 3 name
aaa[root@localhost bash]# echo $name
aaa

列子中我指定了3个输入字符给name变量,当我输入完第三个a时输入命令就自动终止。

1.接下来就来写一个bash命令;bash命令的要求是当输入1时显示当前io信息,输入2时显示cpu信息,输入3显示内存信息,输入其它数字返回错误提示,如果10s未输入则中断输入。

#!/bin/bash

echo "Enter 1 is Select IO ";
echo "Enter 2 is Select CPU";
echo "Enter 3 is Select Memory";

echo "please Enter 1 to 3 "

read -t 10  num;

case $num in

        1)iostat;;

        2)mpstat;;

        3)free;;

        *)echo "no this num";;


esac

注意:case里面的命令不能使用`或者$读取命令,而且直接输入命令即可

2.使用 做交互式输入输出

vim read

#!/bin/bash
read -p "enter word:" a
read -p "enter word:" b
echo you have enter $a,$b
[root@localhost test]# echo -e "1
2
" |./read 
you have enter 1,2

还可以是来自文件的输入

[root@localhost test]# cat a
hello
word
[root@localhost test]# ./read < a
you have enter hello,word

注意:换行符是一个比较特殊符字符( )经常拿来做一些特殊的操作

总结

注意在read命令中参数必须放在变量名之前。

备注:

    作者:pursuer.chen

    博客:http://www.cnblogs.com/chenmh

本站点所有随笔都是原创,欢迎大家转载;但转载时必须注明文章来源,且在文章开头明显处给明链接。

《欢迎交流讨论》

原文地址:https://www.cnblogs.com/chenmh/p/5442688.html