if else语句
if else语句
1、if 语句
最简单的用法就是只使用 if 语句,它的语法格式为:
if condition
then
statement(s)
fi
condition
是判断条件,如果condition
成立(返回“真”),那么then
后边的语句将会被执行;如果condition
不成立(返回“假”),那么不会执行任何语句。- 最后必须以
fi
来闭合,fi 就是 if 倒过来拼写
then
和 if
写在一行,if 和 then 位于同一行的时候,condition
后边的分号;
是必须的
if condition; then
statement(s)
fi
实例:
#!/bin/bash
read a
read b
if (( $a == $b ))
then
echo "a = b"
fi
2、if else 语句
if condition
then
statement1
else
statement2
fi
如果 condition
成立,那么 then
后边的 statement1
语句将会被执行;否则,执行 else
后边的 statement2
语句。
#!/bin/bash
read a
read b
if (( $a == $b ))
then
echo "a = b"
else
echo "Error, a != b"
fi
3、if elif else 语句
if
和 elif
后边都得跟着 then
if condition1
then
statement1
elif condition2
then
statement2
elif condition3
then
statement3
……
else
statementn
fi
整条语句的执行逻辑为:
- 1、如果
condition1
成立,那么就执行if
后边的statement1
;如果condition1
不成立,那么继续执行elif
,判断condition2
。 - 2、如果
condition2
成立,那么就执行statement2
;如果condition2
不成立,那么继续执行后边的elif
,判断condition3
。 - 3、如果
condition3
成立,那么就执行statement3
;如果condition3
不成立,那么继续执行后边的elif
。 - 4、如果所有的
if
和elif
判断都不成立,就进入最后的else
,执行statement
。
实例
#!/bin/bash
printf "Input integer number: "
read num
if ((num==1)); then
echo "Monday"
elif ((num==2)); then
echo "Tuesday"
elif ((num==3)); then
echo "Wednesday"
elif ((num==4)); then
echo "Thursday"
elif ((num==5)); then
echo "Friday"
elif ((num==6)); then
echo "Saturday"
elif ((num==7)); then
echo "Sunday"
else
echo "error"
fi