溫馨提示×

shell if 怎么使用嵌套判斷

小樊
81
2024-10-09 09:57:35
欄目: 編程語言

在Shell腳本中,嵌套if語句是指在一個if語句內(nèi)部再包含一個或多個if語句。這種結構通常用于處理更復雜的條件邏輯。以下是一個嵌套if語句的示例:

#!/bin/bash

num=10

if [ $num -gt 0 ]; then
    echo "Number is greater than 0"
    if [ $num -eq 1 ]; then
        echo "Number is equal to 1"
    else
        echo "Number is greater than 1 but not equal to 10"
    fi
else
    echo "Number is not greater than 0"
fi

在這個示例中,我們首先檢查num是否大于0。如果是,我們進入第一個if語句內(nèi)部,然后檢查num是否等于1。如果等于1,我們輸出"Number is equal to 1";否則,我們輸出"Number is greater than 1 but not equal to 10"。如果num不大于0,我們輸出"Number is not greater than 0"。

0