Shell学习(三)——Shell条件控制和循环语句

参考博客:
[1]Shell脚本的条件控制和循环语句

一、条件控制语句
1、if语句

1.1语法格式:

if [ expression ]
then
    Statement(s) to be executed if expression is true
fi

注意:expression 和方括号([ ])之间必须有空格,否则会有语法错误。
if 语句通过关系运算符判断表达式的真假来决定执行哪个分支。Shell 有三种 if ... else 语句:
if ... fi 语句
if ... else ... fi 语句
if ... elif ... else ... fi 语句

1.2 举例

#!/bin/bash/
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater to b"
else
echo "a is less to b"
fi

if ... else 语句也可以写成一行,以命令的方式来运行:

a=10;b=20;if [$a == $b];then echo "a is equal to b";else echo "a is not equal to b";fi;

if ... else 语句也经常与 test 命令结合使用,作用与上面一样:

a=10
b=20
if test $a == $b
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi 
2、case语句

2.1语法格式

case 变量值 in
值1)
   commands
   ;;
值2)
   commands
   ;;
...
值n)
   commands
   ;;
*)
   commands
  ;;
esac

取值后面必须为关键字 in,每一模式必须以右括号结束。取值可以为变量或常数。匹配发现取值符合某一模式后,其间所有命令开始执行直至 ;;。;; 与其他语言中的 break 类似,意思是跳到整个 case 语句的最后。
取值将检测匹配的每一个模式。一旦模式匹配,则执行完匹配模式相应命令后不再继续其他模式。如果无一匹配模式,使用星号 * 捕获该值,再执行后面的命令。
2.2举例

#!/bin/bash/
grade="B"
case $grade in
"A") echo "Very Good!";;
"B") echo "Good!";;
"C") echo "Come On!";;
*) 
echo "You Must Try!"
echo "Sorry!";;
esac
二、循环语句

1、for语句
1.1语法格式

for 变量 in 列表
do
command1
command2
...
commandN
done

1.2 举例

#!/bin/bash/
for value in 1 2 3 4 5
do
echo "The value is $value"
done

输出结果:
The value is 1
The value is 2
The value is 3
The value is 4
The value is 5
for str in 'This is a string'
do
echo $str
done

输出结果:
This
is
a
string

2、while语句

2.1语法格式

while command
do
   Statement(s) to be executed if command is true
done

命令执行完毕,控制返回循环顶部,从头开始直至测试条件为假。
2.2 举例

#!/bin/bash
c=0;
while [ $c -lt 3 ]
do
echo "Value c is $c"
c=`expr $c + 1`
done

输出结果:
Value c is 0
Value c is 1
Value c is 2

这里由于shell本身不支持算数运算,所以使用expr命令进行自增。
3、until语句

3.1 语法格式

until command
do
   Statement(s) to be executed if command is true
done

until 循环执行一系列命令直至条件为 true 时停止。until 循环与 while 循环在处理方式上刚好相反。
3.2 举例

#!/bin/bash
c=0;
until [ $c -eq 3 ]
do
echo "Value c is $c"
c=`expr $c + 1`
done

输出结果:
Value c is 0
Value c is 1
Value c is 2
4、跳出循环

4.1 break
break命令允许跳出所有循环(终止执行后面的所有循环);在嵌套循环中,break 命令后面还可以跟一个整数,表示跳出第几层循环。
例如:break n表示跳出第n层循环。

#!/bin/bash
i=0
while [ $i -lt 5 ]
do
i=`expr $i + 1`
if [ $i == 3 ]
then
continue
fi
echo -e $i
done

运行结果:
1
2

4.2 continue
continue命令与break命令类似,只有一点差别,它不会跳出所有循环,仅仅跳出当前循环。

#!/bin/bash
i=0
while [ $i -lt 5 ]
do
i=`expr $i + 1`
if [ $i == 3 ]
then
continue
fi
echo -e $i
done

运行结果:
1
2
4
5
原文地址:https://www.cnblogs.com/shujk/p/13411828.html