Shell 编程 if 语句 | 详解 + 实例

  目录

一、基本语法

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。

猜你喜欢

转载自blog.csdn.net/u011074149/article/details/113716153