欢迎登陆真网站,您的到来是我们的荣幸。 登陆 注册 忘记密码? ☆设为首页 △加入收藏
欢迎加入真幸福QQ群
电脑知识: 基础知识 网络技术 操作系统 办公软件 电脑维修 电脑安全 windows7 windows8 windows10 服务器教程 平板电脑 视频播放教程 网络应用 互联网 工具软件 浏览器教程 QQ技巧 输入法教程 影视制作 YY教程 wps教程 word教程 Excel教程 PowerPoint
云南西双版纳特产小花糯玉米真空包装


2016年vr播放器哪个牌子好
Win7系统网关怎么设置?
Win7提示“需要管理员权限”如何解决?
win7开机显示系统更新失败怎么办
win7系统遇到程序突然假死点击关闭按钮无法关闭怎么办
Win8如何启用讲述人功能
Win8打开应用商店显示未连接到Internet怎么办
Win8如何开启或关闭Aero peek预览桌面
win7系统打开word文档提示“版本过低”如何解决
win7系统使用电脑管家删除软件使用记录的方法
在Linux的系统Shell脚本中使用if语句的方法
【 来源:网络 】【 点击:3 】 【 发布时间:2017_03_03 08:59:59 】

   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

本网站由川南居提供技术支持,fkzxf版权所有 浙ICP备12031891号