Bash 指令碼中的多個 if 條件

Muhammad Husnain 2024年2月15日
  1. Bash 程式設計簡介
  2. 編寫 Bash 指令碼
  3. Bash 指令碼中的條件語句
Bash 指令碼中的多個 if 條件

本程式設計教程將討論 bash 中的條件結構,尤其是具有單個和多個條件的 if 條件。

Bash 程式設計簡介

Bash 是 UNIX 和 Linux 作業系統中的一個簡單的命令列直譯器。這個直譯器允許我們使用命令列執行一些命令,這些命令可以通過在一個稱為指令碼的檔案中鍵入它們來共同執行。

shell 指令碼只不過是 bash 命令的集合,可以在 bash 上單獨執行或寫入指令碼檔案,然後,該指令碼檔案可以由 bash 執行。兩種情況下的結果將保持不變。

Bash 是開發人員的關鍵工具,通常用於自動執行需要頻繁執行的重複性任務。Bash 程式設計很容易學習,只需要基本的 bash 命令知識。

編寫 Bash 指令碼

Bash 指令碼寫在一個副檔名為 .script 的檔案中。儘管 Linux 是一個無擴充套件的作業系統,但將此擴充套件新增到你的 bash 指令碼中是一種很好的程式設計約定。

以下命令的功能是建立一個新檔案。

vim myscript.sh

執行此命令後,將建立一個名為 myscript.sh 的檔案並在 vim 編輯器中開啟。下面是每個 bash 指令碼的第一行。

#!/bin/bash

這一行被稱為 shebang,用來告訴作業系統 bash 直譯器的位置。在這一行之後,bash 指令碼的實際程式碼開始。

Bash 指令碼中的條件語句

在 Bash 指令碼中,我們可以有多種型別的條件語句,例如:

  • 如果語句
  • if .. then.. else 語句
  • if .. elif 語句
  • 巢狀 if 語句
  • 案例陳述

我們將討論具有單個和多個條件的 if 語句。在轉向 if 語句之前,讓我們看看 if 語句中一些常用的條件運算子。

運算子號 描述
-eq 如果兩個數字相等,則返回 true
-lt 如果一個數字小於另一個數字,它返回 true
-gt 如果一個數字大於另一個數字,則返回 true
== 如果兩個字串相等,則返回 true
!= 如果兩個字串不相等,則返回 true
! 它否定使用它的表示式。

使用帶有一個條件的 if 語句

語法:

if [ condition-statement ];
    then
        Commands..
fi

讓我們看一個使用 if 條件的示例 bash 指令碼。

指令碼:

#!/bin/bash
echo "Enter your marks out of 100: "
read marks
if [ $marks -gt 100 ]; then
printf "You have entered incorrect marks: $marks\n "
fi

輸出:

使用帶有一個條件的 if 語句

使用帶有多個條件的 if 語句

在前面的示例中,我們使用了單個條件。我們還可以應用多個條件並使用邏輯運算子 ANDOR 運算子將它們分開。

讓我們看看下面的例子。

指令碼:

#!/bin/bash
echo "Enter your marks out of 100: "
read marks
if [[ $marks -gt 100 && $marks -lt 0 ]]; then
printf "You have entered incorrect marks: $marks\n "
fi

輸出:

使用具有多個條件的 if 語句

Muhammad Husnain avatar Muhammad Husnain avatar

Husnain is a professional Software Engineer and a researcher who loves to learn, build, write, and teach. Having worked various jobs in the IT industry, he especially enjoys finding ways to express complex ideas in simple ways through his content. In his free time, Husnain unwinds by thinking about tech fiction to solve problems around him.

LinkedIn

相關文章 - Bash Condition