Linux 管理員 - 條件語句



while 迴圈是操作流的主要控制結構,但是還需要執行邏輯操作。

邏輯操作可以在 BASH 中使用以下結構控制:if、then、else 和 elif 。

If

這非常簡單,將會根據邏輯測試的評估方式進行條件操作。

#!/bin/bash
result = 1

if [ $result -eq 1 ];  
   then 
   echo "Result was true!" 
else  
   echo "Result was false!" 
fi

注意 - Bash 使用幾種不同的相等運算子。在這種情況下,我們使用了“-eq”,對整數進行相等運算。對於字串,我們使用“==”。

elif 用於將邏輯傳遞到另一個條件分支,如下所示 -

#!/bin/bash 
ourColor="red" 
if [ $ourColor == "black" ]; 
   then 
   echo "Too dark" 
elif [ $ourColor == "white" ]; 
   then 
   echo "Too plain!" 
elif [ $ourColor != "gray" ]; 
   then 
   echo "Too colorful"
else 
   echo "Let's make it" $ourColor 
fi

在我們決定灰度之前,我們有些偏頗的指令碼不會滿足。

linux_admin_shell_scripting.htm
廣告
© . All rights reserved.