Shell编程-if else语句

时间:2020-02-23 14:45:08  来源:igfitidea点击:

在本教程中,我们将学习Shell编程中的If Else条件语句。

我们使用If语句根据某些条件来决定是否执行代码块。

if语句

以下是if语句的语法。

if [ condition ]
then
  # if block code
fi

其中," condition"是某种条件,如果if评估为true,则执行if块代码,否则将被忽略。

fi(if的相反)标记if语句的结尾。

例1:编写一个Shell脚本来检查两个数字是否相等

在下面的示例中,我们将使用" =="等于运算符来检查两个数字是否相等。

#!/bin/sh

# take two numbers from the user
echo "Enter two numbers: "
read a b

# check
if [ $a == $b ]
then
  echo "Numbers are equal."
fi

echo "End of script."
$sh if.sh 
Enter two numbers: 
10 20
End of script.

$sh if.sh 
Enter two numbers: 
10 10
Numbers are equal.
End of script.

在第一次运行中,如果if块不执行为10,则不等于20。
在第二次运行中,如果if块执行为10,则等于10。

if else语句

以下是if else语句的语法。

if [ condition ]
then
  # if block code
else
  # else block code
fi

其中," condition"是某种条件,如果if评估为true,则执行if块代码,否则执行if块代码。

例2:编写Shell脚本以检查两个数字是否相等,是否使用if else语句

在下面的示例中,如果它们相等,则将打印"数字相等",否则,将显示"数字不相等"。

#!/bin/sh

# take two numbers from the user
echo "Enter two numbers: "
read a b

# check
if [ $a == $b ]
then
  echo "Numbers are equal."
else
  echo "Numbers are not equal."
fi

echo "End of script."
$sh if-else.sh 
Enter two numbers: 
10 20
Numbers are not equal.
End of script.

if elif else语句

以下是if elif else语句的语法。

if [ condition ]
then
  # if block code
elif [ condition2 ]
then
  # elif block code
else
  # else block code
fi

其中," condition"是一些条件,如果if评估为true,则执行if块代码。
如果为假,则检查elif条件。
如果那也是错误的,那么我们执行else块(如果存在)。

例3:编写Shell脚本以检查数字是否为奇数,偶数或者零

我们将使用模数运算符"%"来检查数字是奇数还是偶数。

如果一个数字可被2整除并且没有余数,则它是一个偶数。

#!/bin/sh

# take a numbers from the user
echo "Enter a number: "
read a

# check
if [ $a == 0 ]
then
  echo "It's zero."
elif [ `expr $a % 2` == 0 ]
then
  echo "It's even."
else
  echo "It's odd."
fi

echo "End of script."
$sh if-elif-else.sh 
Enter a number: 
0
It's zero.
End of script.

$sh if-elif-else.sh 
Enter a number: 
10
It's even.
End of script.

$sh if-elif-else.sh 
Enter a number: 
11
It's odd.
End of script.