第7章 流程控制(重点)
第7章 流程控制(重点)
7.1 if判断
1.基本语法
if [ 条件判断式 ];then
程序
fi
或者
if [ 条件判断式 ]
then
程序
fi
注意事项:
(1)[ 条件判断式 ],中括号和条件判断式之间必须有空格
(2)if后要有空格
2.案例实操
(1)输入一个ip地址,如果可以ping通,则输出Host is online,如果ping不通,则输出Host is offline。
[root@localhost ~]# touch if.sh
[root@localhost ~]# vim if.sh
#!/bin/bash
ping -c4 -w4 $1 > /dev/null
if [ $? -eq 0 ]
then
echo "Host $1 is online"
else
echo "Host $1 is offline"
fi
[root@localhost ~]# chmod a+x if.sh
[root@localhost ~]# ./if.sh 192.168.40.135
Host 192.168.40.135 is online
[root@localhost ~]# ./if.sh 192.168.0.104
Host 192.168.0.104 is online
[root@localhost ~]# ./if.sh 192.168.40.136
Host 192.168.40.136 is offline
7.2 case语句
1.基本语法
case $变量名 in
"值1")
如果变量的值等于值1,则执行程序1
;;
"值2”)
如果变量的值等于值2,则执行程序2
;;
*)
如果变量的值都不是以上的值,则执行此程序
;;
esac
注意事项:
(1)case行尾必须为单词"in",每一个模式匹配必须以右括号“)”结束
(2)双分号";;"表示命令序列结束,相当于java中的break
(3)最后的"*)"表示是默认模式,相当于java的default
2.案例实操
(1)输入一个数字,如果是1,则输出one,如果是2,则输出two,如果是其他,输出other
[root@localhost ~]# touch case.sh
[root@localhost ~]# vim case.sh
#!/bin/bash
case $1 in
"1")
echo "one"
;;
"2")
echo "two"
;;
*)
echo "other"
;;
esac
[root@localhost ~]# chmod a+x case.sh
[root@localhost ~]# ./case.sh 1
one
[root@localhost ~]# ./case.sh 2
two
[root@localhost ~]# ./case.sh 3
other
7.3 for循环
1.基本语法1
for (( 初始值;循环控制条件;变量变化 ))
do
程序
done
2.案例实操
(1)从1加到100
[root@localhost ~]# touch for1.sh
[root@localhost ~]# vim for1.sh
#!/bin/bash
s=0
for ((i=0;i<=100;i++))
do
s=$[$s+$i]
done
echo $s
[root@localhost ~]# chmod a+x for1.sh
[root@localhost ~]# ./for1.sh
5050
3.基本语法2
for 变量 in 值1 值2 值3...
do
程序
done
4.案例实操
(1)ping一段连续的ip地址,判断主机是否在线
[root@localhost ~]# touch for2.sh
[root@localhost ~]# vim for2.sh
#!/bin/bash
for i in $*
do
ping -c4 $i > /dev/null
if [ $? -eq 0 ]
then
echo "Host $i is online"
else
echo "Host $i is offline"
fi
done
[root@localhost ~]# chmod a+x for2.sh
[root@localhost ~]# ./for2.sh 192.168.40.134 192.168.40.135 192.168.40.136
Host 192.168.40.134 is offline
Host 192.168.40.135 is online
Host 192.168.40.136 is offline
(2)比较$*和$@的区别
(a)$*和$@都表示传递给函数或脚本的所有参数,不被双引号“”包含时,都以$1$2...$n的形式输出送有参数
[root@localhost ~]# touch for.sh
[root@localhost ~]# vim for.sh
#!/bin/bash
for i in $*
do
echo "This is $i"
done
for j in $@
do
echo "This is $j"
done
[root@localhost ~]# chmod a+x for.sh
[root@localhost ~]# ./for.sh aaa bbb ccc
This is aaa
This is bbb
This is ccc
This is aaa
This is bbb
This is ccc
(b)当它们被双引号""包含时,"$*"会将所有的参数作为一个整体,以"$1 $2...$n"的形式输出所有参数;"$@"会将各个参数分开,以"$1""$2"..."$n"的形式输出所有参数
[root@localhost ~]# vim for.sh
#!/bin/bash
for i in "$*"
do
echo "This is $i"
done
for j in "$@"
do
echo "This is $j"
done
[root@localhost ~]# ./for.sh aaa bbb ccc
This is aaa bbb ccc
This is aaa
This is bbb
This is ccc
7.4 while循环
1.基本语法
while [ 条件判断式 ]
do
程序
done
2.案例实操
(1)从1加到100
[root@localhost ~]# touch while.sh
[root@localhost ~]# vim while.sh
#!/bin/bash
s=0
i=1
while [ $i -le 100 ]
do
s=$[$s+$i]
i=$[$i+1]
done
echo $s
[root@localhost ~]# chmod a+x while.sh
[root@localhost ~]# ./while.sh
5050