温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

在Linux系统中Shell脚本使用if语句的方法

发布时间:2021-08-03 10:31:17 来源:亿速云 阅读:144 作者:chen 栏目:系统运维

这篇文章主要讲解了“在Linux系统中Shell脚本使用if语句的方法”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“在Linux系统中Shell脚本使用if语句的方法”吧!

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

if 语句的语法:

   

代码如下:

if [ 判断条件 ]
   then
           command1
           command2
           ……..
           last_command
   fi</p> <p>Example:</p> <p>    #!/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
          &hellip;&hellip;..
          last_command
   else
          command1
          command2
          &hellip;&hellip;..
          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
          &hellip;&hellip;..
          last_command
   elif [ 判断条件2 ]
   then
           command1
           command2
           &hellip;&hellip;..
           last_command
   else
   command1
   command2
   &hellip;&hellip;..
   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
           &hellip;&hellip;..
           last_command
   else
   if [ 判断条件2 ]
   then
           command1
           command2
           &hellip;&hellip;..
           last_command
   else
           command1
           command2
            &hellip;&hellip;..
            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系统中Shell脚本使用if语句的方法这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI