条件判断:if语句

语法格式:

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 语句

示例:

#!/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 命令结合使用,作用与上面一样:

#!/bin/bash/

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

分支控制:case语句

case ... esac 与其他语言中的 switch ... case 语句类似,是一种多分枝选择结构。

示例:

#!/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

转换成C语言是:

#include <stdio.h>
int main(){
char grade = 'B';
switch(grade){
case 'A': printf("Very Good!");break;
case 'B': printf("Very Good!");break;
case 'C': printf("Very Good!");break;
default:
printf("You Must Try!");
printf("Sorry!");
break;
}
return 0;
}

对比看就很容易理解了。很相似,只是格式不一样。

需要注意的是:

取值后面必须为关键字 in,每一模式必须以右括号结束。取值可以为变量或常数。匹配发现取值符合某一模式后,其间所有命令开始执行直至 ;;;; 与其他语言中的 break 类似,意思是跳到整个 case 语句的最后。

取值将检测匹配的每一个模式。一旦模式匹配,则执行完匹配模式相应命令后不再继续其他模式。如果无一匹配模式,使用星号 * 捕获该值,再执行后面的命令。

再举一个例子:

#!/bin/bash
option="${1}"
case ${option} in
"-f") FILE="${2}"
echo "File name is $FILE"
;;
"-d") DIR="${2}"
echo "Dir name is $DIR"
;;
*)
echo "`basename ${0}`:usage: [-f file] | [-d directory]"
exit 1 # Command to come out of the program with status 1
;;
esac

运行结果:

$./test.sh
test.sh: usage: [ -f filename ] | [ -d directory ] ./test.sh -f index.html
File name is index.html

这里用到了特殊变量${1},指的是获取命令行的第一个参数。

for循环

shell的for循环与c、php等语言不同,同Python很类似。下面是语法格式:

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

示例:

#!/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

遍历目录下的文件:

#!/bin/bash
for FILE in *
do
echo $FILE
done

上面的代码将遍历当前目录下所有的文件。在Linux下,可以改为其他目录试试。

遍历文件内容:

city.txt

beijing
tianjin
shanghai
#!/bin/bash

citys=`cat city.txt`
for city in $citys
echo $city
done

输出:

beijing
tianjin
shanghai

while循环

只要while后面的条件满足,就一直执行do里面的代码块。

其格式为:

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

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

示例:

#!/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命令进行自增。

until循环

until 循环执行一系列命令直至条件为 true 时停止。until 循环与 while 循环在处理方式上刚好相反。一般while循环优于until循环,但在某些时候,也只是极少数情况下,until 循环更加有用。

将上面while循环的例子改改,就能达到一样的效果:

#!/bin/bash

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

首先do里面的语句块一直在运行,直到满足了until的条件就停止。

输出:

Value c is 0
Value c is 1
Value c is 2

跳出循环

在循环过程中,有时候需要在未达到循环结束条件时强制跳出循环,像大多数编程语言一样,Shell也使用 break 和 continue 来跳出循环。

break

break命令允许跳出所有循环(终止执行后面的所有循环)。

#!/bin/bash

i=0
while [ $i -lt 5 ]
do
i=`expr $i + 1` if [ $i == 3 ]
then
break
fi
echo -e $i
done

运行结果:

1
2

在嵌套循环中,break 命令后面还可以跟一个整数,表示跳出第几层循环。例如:

break n

表示跳出第 n 层循环。

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

Shell脚本学习系列教程github: https://github.com/52fhy/shell-book

04- Shell脚本学习--条件控制和循环语句的更多相关文章

  1. Shell脚本的条件控制和循环语句

    条件判断:if语句 语法格式: if [ expression ] then Statement(s) to be executed if expression is true fi 注意:expre ...

  2. shell脚本学习—条件测试和循环语句

    条件测试 1. 条件测试:test [ 命令test或[可以测试一个条件是否成立,如果测试结果为真,则该命令的Exit Status为0,如果测试结果为假, 则命令的Exit Status为1(注意与 ...

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

    参考博客: [1]Shell脚本的条件控制和循环语句 一.条件控制语句 1.if语句 1.1语法格式: if [ expression ] then Statement(s) to be execut ...

  4. Python - 条件控制、循环语句 - 第十二天

    Python 条件控制.循环语句 end 关键字 关键字end可以用于将结果输出到同一行,或者在输出的末尾添加不同的字符,实例如下: Python 条件语句是通过一条或多条语句的执行结果(True 或 ...

  5. Shell脚本学习 - 流程控制和函数

    继续Shell的学习.上两篇是关于基本数据类型,基本语法以及运算符相关,这一篇是流程控制相关(if, for, while) 流程控制 if else 流程控制不可为空,如果else没有语句执行,就不 ...

  6. Shell中的条件测试和循环语句

    1.条件测试:test或[ 如果测试结果为真,则该命令的Exit Status为0,如果测试结果为假,则命令的Exit Status为0 运行结果: 带与.或.非的测试命令[ ! EXPR ] : E ...

  7. Python条件控制与循环语句

    1. 条件控制 # if-elif-else结构 age = 12 if age < 4: price = 0 elif age < 18: price = 5 else: price = ...

  8. If 条件控制 & while循环语句

    Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块. 可以通过下图来简单了解条件语句的执行过程: if 语句 Python中if语句的一般形式如下所示: i ...

  9. Python学习--04条件控制与循环结构

    Python学习--04条件控制与循环结构 条件控制 在Python程序中,用if语句实现条件控制. 语法格式: if <条件判断1>: <执行1> elif <条件判断 ...

随机推荐

  1. Lessons Learned 1(敏捷项目中的变更影响分析)

    问题/现象: 业务信息流转的某些环节,会向相关人员发送通知邮件,邮件中附带有链接,供相关人员进入察看或处理业务.客户要求邮件中的链接,需要进行限制,只有特定人员才能进入处理或察看.总管想了想,应道没问 ...

  2. 4580: [Usaco2016 Open]248

    Description Bessie likes downloading games to play on her cell phone, even though she does find the ...

  3. C# "=="、Equals()、ReferenceEquals()区别

    对于值类型: ; ; 1.== 比较的是值内容 2.age2.Equals(age1) = false; Equals比较前需要转换成同类型,age1(int型)需显示转换成byte型 3.age1. ...

  4. Hibernate-list()与iterate()方法的区别

    对于list方法而言,实际上Hibernate是通过一条Select SQL获取所有的记录.并将其读出,填入到POJO中返回.而iterate 方法,则是首先通过一条Select SQL 获取所有符合 ...

  5. mac系统 下 npm 安装 bower报错

    在mac终端运行 sudo npm install -g bower (安装之前你要确定你已经成功安装了node 和 git) 然后会报错 like this: npm ERR! Darwin 15. ...

  6. JS获取各种浏览器窗口大小的方法

    常用:JS 获取浏览器窗口大小复制代码 代码如下:// 获取窗口宽度if (window.innerWidth)winWidth = window.innerWidth;else if ((docum ...

  7. 在VS2010下编译和使用tesseract_ocr识别验证码

    对于自动识别验证码,使用trsseract是个不错的选择,有兴趣的的朋友可以试试. 编译tesseract 官网提供了vs2008的编译说明和工程,但在vs2010下的编译时基本相同的,因此我使用的方 ...

  8. Boost 安装

    1.下载boost Windows版,如:boost_1_55_0: 2.运行boostrap.bat,会生成bjam.exe: 3.运行bjam.exe(时间会比较长),会生成一个stage目录里面 ...

  9. C++的四种cast操作符的区别--类型转换(转)

    转自:     http://welfare.cnblogs.com/articles/336091.html Q:什么是C风格转换?什么是static_cast, dynamic_cast 以及 r ...

  10. Win7系统修改hosts文件不能保存的解决方法

    地址:http://jingyan.baidu.com/album/e5c39bf56564a539d7603312.html