一、read的作用
read能将用户通过键盘输入的字符串保存在后面所跟的变量里面
[root@TESTHOST scripts]# read Num
1
[root@TESTHOST scripts]# echo $Num
1
[root@TESTHOST scripts]# read Num
123
[root@TESTHOST scripts]# echo $Num
123
通过read可以输入任何信息给脚本,也可以从命令行读入多个值传递给变量
[root@TESTHOST scripts]# read Num Name Year
1 Arvin 2015
[root@TESTHOST scripts]# echo $Num $Name $Year
1 Arvin 2015
----------------------------------------------
[root@TESTHOST scripts]# read Num Name Year
1 Arvin 2015 2014
[root@TESTHOST scripts]# echo $Num
1
[root@TESTHOST scripts]# echo $Name
Arvin
[root@TESTHOST scripts]# echo $Year
2015 2014 #这里把最后两个字符传递给了变量Year
二、read常用参数
-p():曾加提示信息 # 另echo -n 显示信息后,不换行
-t:指定超时时间,在指定的时间内read命令未交互,则超时退出
三、示例及练习
示例1:
#!/bin/bash
#
read –p “Input a character:”Char
case $Char in[0-9])
echo “A digit.” ;;
[a-z])
echo “A lower.” ;;
[A-Z])
echo “A upper.” ;;
[[:punct:]])
echo “A punction.” ;;
*)
echo “A special char.” ;;
esac
示例2:
#!/bin/bash
#
read -p "Do you agree [yes|no]?: " YesNo
case $YesNo in
y|Y|[Yy]es)
echo "Agreed, proceed." ;;
n|N|[nN]o)
echo "Disagreed, can't proceed." ;;
*)
echo "Invalid input." ;;
esac
例子3:写一个脚本
1、显示如下菜单给用户:
m|M) show memory usages;
d|D) show disk usages;
q|Q) quit
2、如果用户选择了第一项,则显示内存使用信息;
如果选择了第二项,则显示磁盘挂载及使用相关信息;
如果是第三项,退出,并显示选择退出;
其它任何内容,均说明错误选项;
#!/bin/bash
#
cat << EOF
m|M) show memory usages;
d|D) show disk usages;
q|Q) quit
EOF
read -t 20 -p "Press a choice:" Key
if [ -z $Key ]; then
echo "No choice,quit."
Key=q
exit 3
fi
case $Key in
m|M)
free -m
;;
d|D)
du -lh
;;
q|Q)
echo "Quit."
exit 5
;;
*)
echo "Invalid input."
exit 7
;;
esac
练习1:写一个脚本,能接受参数gzip、bzip2或xz,而后能将/etc/目录归档备份至/backup目录,并以参数指定的形式压缩存放;文件名称包含脚本执行时刻的时间
#!/bin/bash
# Date: 2015-04-13
# Description:
# Version: 1.0
if [ ! -e /backup ];then #这里可以用[ -d /backup ] || mkdir /backup 替代
mkdir /backup
fi
read -t 20 -p "Press a command{gzip|bzip2|xz}:" Command #read,20秒超时,给command赋值
Command=$1
if [ -z $1 ]; then #如果脚本给定的是空值,则默认输入gzip
Command=gzip
fi
case $Command in
gzip)
tar czfP /backup/backupfile-`date +%F-%H-%M-%S`.tar.gz /etc/
Ret=$?
;;
bzip2)
tar cjfP /backup/backupfile-`date +%F-%H-%M-%S`.tar.bz2 /etc/
Ret=$?
;;
xz)
tar cJfP /backup/backupfile-`date +%F-%H-%M-%S`.tar.xz /etc/
Ret=$?
;;
*)
echo "Usage:`basename $0`{gzip | bzip2 | xz }."
exit 5
;;
esac
[ $Ret -eq 0 ] && echo "Backup etc successfully.($Command)" #每一个分支都有将执行返回值赋值给Ret,当Ret为0时,即知道变量Command是gzip、bzip2、xz中哪一个
来源:oschina
链接:https://my.oschina.net/u/4350184/blog/4317867