Shell学习笔记(二)

if 语句

最简单的用法就是只使用 if 语句,它的语法格式为:

if  condition
then
    statement(s)
fi

condition是判断条件,如果 condition 成立(返回“真”),那么 then 后边的语句将会被执行;如果 condition 不成立(返回“假”),那么不会执行任何语句。

从本质上讲,if 检测的是命令的退出状态

注意,最后必须以fi来闭合,fi 就是 if 倒过来拼写。也正是有了 fi 来结尾,所以即使有多条语句也不需要用{ }包围起来。

也可以将 then 和 if 写在一行:

if  condition;  then
    statement(s)
fi

请注意 condition 后边的分号;,当 if 和 then 位于同一行的时候,这个分号是必须的,否则会有语法错误。

实例1

下面的例子使用 if 语句来比较两个数字的大小:

#!/bin/bash
echo "Hello world"
read a
read b
if (( $a == $b ))
then
    echo "a和b相等"
fi

执行结果

[root@sijizhen demo]# ./backup.sh
Hello world
55
55
a和b相等

if(())是一种数学计算命令,它除了可以进行最基本的加减乘除运算,还可以进行大于、小于、等于等关系运算,以及与、或、非逻辑运算。当 a 和 b 相等时,(( $a == $b ))判断条件成立,进入 if,执行 then 后边的 echo 语句。

if else 语句

if  condition
then
   statement1
else
   statement2
fi

如果 condition 成立,那么 then 后边的 statement1 语句将会被执行;否则,执行 else 后边的 statement2 语句。

举个例子

#!/bin/bash
read a
read b
if (( $a == $b ))
then
    echo "a和b相等"
else
    echo "a和b不相等,输入错误"
fi

执行结果:

[root@sijizhen demo]# ./backup.sh
Hello world
66
65
a和b不相等,输入错误

if elif else 语句

Shell 支持任意数目的分支,当分支比较多时,可以使用 if elif else 结构,它的格式为:

if  condition1
then
   statement1
elif condition2
then
    statement2
elif condition3
then
    statement3
……
else
   statementn
fi

注意,if 和 elif 后边都得跟着 then。

整条语句的执行逻辑为:

  • 如果 condition1 成立,那么就执行 if 后边的 statement1;如果 condition1 不成立,那么继续执行 elif,判断 condition2。
  • 如果 condition2 成立,那么就执行 statement2;如果 condition2 不成立,那么继续执行后边的 elif,判断 condition3。
  • 如果 condition3 成立,那么就执行 statement3;如果 condition3 不成立,那么继续执行后边的 elif。
  • 如果所有的 if 和 elif 判断都不成立,就进入最后的 else,执行 statementn。

举个例子,输入年龄,输出对应的人生阶段:

#!/bin/bash
read age
if (( $age <= 2 )); then
    echo "婴儿"
elif (( $age >= 3 && $age <= 8 )); then
    echo "幼儿"
elif (( $age >= 9 && $age <= 17 )); then
    echo "少年"
elif (( $age >= 18 && $age <=25 )); then
    echo "成年"
elif (( $age >= 26 && $age <= 40 )); then
    echo "青年"
elif (( $age >= 41 && $age <= 60 )); then
    echo "中年"
else
    echo "老年"
fi

Shell while循环详解

while 循环是 Shell 脚本中最简单的一种循环,当条件满足时,while 重复地执行一组语句,当条件不满足时,就退出 while 循环。

Shell while 循环的用法如下:

while condition
do
    statements
done

condition表示判断条件,statements表示要执行的语句(可以只有一条,也可以有多条),dodone都是 Shell 中的关键字。

while 循环的执行流程为:

  • 先对 condition 进行判断,如果该条件成立,就进入循环,执行 while 循环体中的语句,也就是 do 和 done 之间的语句。这样就完成了一次循环。
  • 每一次执行到 done 的时候都会重新判断 condition 是否成立,如果成立,就进入下一次循环,继续执行 do 和 done 之间的语句,如果不成立,就结束整个 while 循环,执行 done 后面的其它 Shell 代码。
  • 如果一开始 condition 就不成立,那么程序就不会进入循环体,do 和 done 之间的语句就没有执行的机会。

注意,在 while 循环体中必须有相应的语句使得 condition 越来越趋近于“不成立”,只有这样才能最终退出循环,否则 while 就成了死循环,会一直执行下去,永无休止

 

posted @ 2019-03-27 17:52  四季镇  阅读(229)  评论(0编辑  收藏  举报