手机
当前位置:查字典教程网 >电脑 >服务器_操作系统教程 >在Linux的系统Shell脚本中使用if语句的方法
在Linux的系统Shell脚本中使用if语句的方法
摘要:BourneShell的if语句和大部分编程语言一样-检测条件是否真实,如果条件为真,shell会执行这个if语句指定的代码块,如果条件为假...

Bourne Shell 的 if 语句和大部分编程语言一样 - 检测条件是否真实,如果条件为真,shell 会执行这个 if 语句指定的代码块,如果条件为假,shell 就会跳过 if 代码块,继续执行之后的代码。

2015615170540856.png (300×358)

if 语句的语法:

代码如下:

if [ 判断条件 ]

then

command1

command2

……..

last_command

fi

Example:

#!/bin/bash

number=150

if [ $number -eq 150 ]

then

echo "Number is 150"

fi

if-else 语句:

除了标准的 if 语句之外,我们还可以加入 else 代码块来扩展 if 语句。这么做的主要目的是:如果 if 条件为真,执行 if 语句里的代码块,如果 if 条件为假,执行 else 语句里的代码块。

语法:

代码如下:

if [ 判断条件 ]

then

command1

command2

……..

last_command

else

command1

command2

……..

last_command

fi

Example:

代码如下:

#!/bin/bash

number=150

if [ $number -gt 250 ]

then

echo "Number is greater"

else

echo "Number is smaller"

fi

If..elif..else..fi 语句 (简写的 else if)

Bourne Shell 的 if 语句语法中,else 语句里的代码块会在 if 条件为假时执行。我们还可以将 if 语句嵌套到一起,来实现多重条件的检测。我们可以使用 elif 语句(else if 的缩写)来构建多重条件的检测。

语法 :

代码如下:

if [ 判断条件1 ]

then

command1

command2

……..

last_command

elif [ 判断条件2 ]

then

command1

command2

……..

last_command

else

command1

command2

……..

last_command

fi

Example :

代码如下:

#!/bin/bash

number=150

if [ $number -gt 300 ]

then

echo "Number is greater"

elif [ $number -lt 300 ]

then

echo "Number is Smaller"

else

echo "Number is equal to actual value"

fi

多重 if 语句 :

If 和 else 语句可以在一个 bash 脚本里相互嵌套。关键词 “fi” 表示里层 if 语句的结束,所有 if 语句必须使用 关键词 “fi” 来结束。

基本 if 语句的嵌套语法:

代码如下:

if [ 判断条件1 ]

then

command1

command2

……..

last_command

else

if [ 判断条件2 ]

then

command1

command2

……..

last_command

else

command1

command2

……..

last_command

fi

fi

Example:

代码如下:

#!/bin/bash

number=150

if [ $number -eq 150 ]

then

echo "Number is 150"

else

if [ $number -gt 150 ]

then

echo "Number is greater"

else

echo "'Number is smaller"

fi

fi

【在Linux的系统Shell脚本中使用if语句的方法】相关文章:

在Linux系统中使用dupeGuru查找并移除重复文件的教程

在Linux系统中安装使用恶意软件扫描工具及杀毒引擎的教程

在Ubuntu系统上安装KDE图形化界面的教程

在Linux终端中使用后台运行模式启动程序的方法

在Linux中使用Alpine工具在命令行里访问Gmail的教程

Linux系统下在命令行中压缩JPEG图像的方法

Linux系统被入侵后使用lsof命令恢复被删除日志的方法

在Linux中如何恢复被删除的文件

Linux通过shell脚本创建SVN版本库简化创建过程

在Ubuntu系统的电脑上开启无线热点全攻略

精品推荐
分类导航