shell脚本之五:bash内置核心命令read基础及实践,


五、bash内置核心命令read基础及实践

(一)read介绍

read 读入,读取用户输入。

-p 输入提示;

-t 等待用户输入的时间。

[root@centos6-kvm3 scripts]# read -t 30 -p "请输入一个数字:" a
请输入一个数字:14
[root@centos6-kvm3 scripts]# echo $a
14

(二)read 读入的作用:

read读入作用为:交互。

1、定义变量案例

[root@centos6-kvm3 scripts]# vim test5.sh
#!/bin/bash
a=6
b=2
echo "a-b=$(($a-$b))"
echo "a+b=$(($a+$b))"
echo "a*b=$(($a*$b))"
echo "a/b=$(($a/$b))"
echo "a**b=$(($a**$b))"
echo "a%b=$(($a%$b))"                 
[root@centos6-kvm3 scripts]# 
[root@centos6-kvm3 scripts]# sh test5.sh 
a-b=4
a+b=8
a*b=12
a/b=3
a**b=36
a%b=0

2、变量交互输入案例

[root@centos6-kvm3 scripts]# vim test5.sh
#!/bin/bash
read -p "请输入两个参数:" a b
echo "a-b=$(($a-$b))"
echo "a+b=$(($a+$b))"
echo "a*b=$(($a*$b))"
echo "a/b=$(($a/$b))"
echo "a**b=$(($a**$b))"
echo "a%b=$(($a%$b))"
                      
[root@centos6-kvm3 scripts]# sh test5.sh
请输入两个参数:4 5
a-b=-1
a+b=9
a*b=20
a/b=0
a**b=1024
a%b=4

3、变量参数输入案例

[root@centos6-kvm3 scripts]# vim test5.sh 
#!/bin/bash
a=$1
b=$2
echo "a-b=$(($a-$b))"
echo "a+b=$(($a+$b))"
echo "a*b=$(($a*$b))"
echo "a/b=$(($a/$b))"
echo "a**b=$(($a**$b))"
echo "a%b=$(($a%$b))"                     
[root@centos6-kvm3 scripts]# 
[root@centos6-kvm3 scripts]# 
[root@centos6-kvm3 scripts]# sh test5.sh 5 9
a-b=-4
a+b=14
a*b=45
a/b=0
a**b=1953125
a%b=5

(三)read 的企业应用案例:

[root@centos6-kvm3 scripts]# cat select.sh 
#!/bin/bash
cat << EOF
1.install lamp
2.install lnmp
3.exit
EOF
read -p "请输入一个序号:" num
expr 2 + $num &>/dev/null
if [ $? -ne 0 ]
then
   echo "usage:$0{1|2|3}"
   exit 1
fi

if [ $num -eq 1 ]
then
   echo "install lamp..."
elif [ $num -eq 2 ]
then
   echo "install lnmp ..."
elif [ $num -eq 3 ]
then
   echo "bye..."
   exit
else
   echo "usage:$0{1|2|3}"
   exit 1
fi

[root@centos6-kvm3 scripts]# sh select.sh
1.install lamp
2.install lnmp
3.exit
请输入一个序号:a
usage:select.sh{1|2|3}
[root@centos6-kvm3 scripts]# sh select.sh
1.install lamp
2.install lnmp
3.exit
请输入一个序号:4
usage:select.sh{1|2|3}
[root@centos6-kvm3 scripts]# sh select.sh
1.install lamp
2.install lnmp
3.exit
请输入一个序号:3
bye...
[root@centos6-kvm3 scripts]# sh select.sh
1.install lamp
2.install lnmp
3.exit
请输入一个序号:2
install lnmp ...
[root@centos6-kvm3 scripts]# 

相关内容

    暂无相关文章