1. 程式人生 > 其它 >Shell 程式設計 if 語句 | 詳解 + 例項

Shell 程式設計 if 語句 | 詳解 + 例項

技術標籤:LinuxShell if 語句if else 語句Shell 邏輯控制語句Shell 程式設計Shell if else語句

目錄

一、基本語法

1.1 if

1.2 if else

1.3 if elif

二、例項

2.1 if 語句

2.2 if else 語句

2.3 if elif 語句

三、總結


在 Shell 程式設計中,在判斷的時候經常使用 if 語句,但是,Shell 中的 if 語句與 C/C++/Java 等語言中的形式還有有些差別的,下面結合例項進行說明。

一、基本語法

if 語句主要有一下幾種形式。

1.1 if

(1)形式一

if condition; then
    符合 condition 的執行語句
fi

注意:結尾是將 if 倒過來寫 fi 作為結束標誌。

(2)形式二

可以將 then 寫到與 if 在一行,也可以分行寫,如下所示:

if condition
then
    符合 condition 的執行語句
fi

1.2 if else

單獨的一個 if else 語句,如下所示:

if condition
then
    符合 condition 的執行語句
else
    不符合 condition 的執行語句
fi

這裡 then 也可以寫到與 if 在一行中。

1.3 if elif

注意:Shell 裡將 else if 簡寫為 elif,elif 也要有 then,如下所示:

if condition_1
then
    符合 condition_1 的執行語句
elif condition_2
then
    符合 condition_2 的執行語句
else 
    不符合 condition_1 和 condition_2 的執行語句
fi

當然,還有更多的組合形式,這裡就不一一說明了。

二、例項

2.1 if 語句

#!/bin/bash

file="/root"

#形式一
if [ -d $file ]; then
    echo "$file is directory!"
fi

#形式二
if [ -d $file ]
then
    echo "$file is directory!"
fi

2.2 if else 語句

#!/bin/bash

file="/root"
if [ -d $file ]
then
    echo "$file is directory!"
else
    echo "$file is not directory!"
fi

2.3 if elif 語句

#!/bin/bash

file="/root"
if [ -f $file ]
then
    echo "$file is regular file!"
elif [ -d $file ]
then
    echo "$file is directory!"
else
    echo "$file is not regular file and directory"
fi

三、總結

if 語句判斷邏輯各種程式語言都是通用的,在 Shell 中要注意if語句結尾使用 fi(if 倒過來寫),else if 應寫成 elif ,還有在寫 if 和 elif 時別忘記 then。