一文教你入门shell脚本7.0——Shell 判断语句if else语句

if else语句

1、if 语句

最简单的用法就是只使用 if 语句,它的语法格式为:

if  condition
then
    statement(s)
fi
  • condition是判断条件,如果 condition 成立(返回“真”),那么 then 后边的语句将会被执行;如果condition 不成立(返回“假”),那么不会执行任何语句。
  • 最后必须以fi来闭合,fi 就是 if 倒过来拼写

thenif 写在一行,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 语句

ifelif 后边都得跟着 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、如果所有的 ifelif 判断都不成立,就进入最后的 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

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/JMW1407/article/details/107489313