国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Linux > 正文

在Linux的系統Shell腳本中使用if語句的方法

2020-05-27 13:01:13
字體:
來源:轉載
供稿:網友

   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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 鹰潭市| 韩城市| 咸丰县| 轮台县| 长兴县| 连城县| 兴宁市| 静乐县| 广德县| 顺义区| 太仆寺旗| 南涧| 沙田区| 常熟市| 绿春县| 筠连县| 嘉荫县| 南汇区| 合作市| 柳州市| 仙桃市| 武穴市| 黄大仙区| 绥棱县| 崇仁县| 紫金县| 东山县| 大同县| 崇仁县| 乐安县| 门头沟区| 集安市| 石门县| 芜湖县| 体育| 平遥县| 涞水县| 泽州县| 若羌县| 东城区| 海宁市|