Shell script conditional if statement, case statement

One, if statement

1. Single branch if statement

Conditional judgment statement, use conditions to control whether to execute the command or not.
Insert picture description here
Statement format:

if 条件测试                #用来筛选是否进入命令序列
     then 命令序列         #这里是满足条件测试后执行的命令
fi                        #fi是结尾

Note: If you start with if you must remember to end with fi. These two are a pair. If you write less, you will get an error.
Example
Insert picture description here
Here -gt is greater than, -ge is greater than or equal to

2. Double branch if statement

General format:

if 条件测试                #用来筛选是否进入命令序列
     then 命令序列1         #这里是满足条件测试后执行的命令
     else 命令序列2        #这是是不满足条件所执行的命令,如果没有命令,则不执行直接结束。 
fi                        #fi是结尾

Insert picture description here

3. Multi-branch structure

Due to the need for more refined judgment partitions, a multi-branch line structure is used for classification output.
That is: after the first condition test is met, screening is performed again, and so on.

Insert picture description here
Here is a simple multi-branch structure to experiment



#!/bin/bash
#学习成绩的分档
read -p "请输入您的分数(0-100):" score
if [ $score -ge 0 ]  &&  [ $score -le 100 ]
then
  if [ $score -ge 90 ] && [ $score -le 100 ]
  then
     echo " 恭喜得到$score分,棒! "
  elif [ $score -ge 70 ] && [ $score -le 89 ]
  then
     echo "得到$score分,再接再厉!"
  elif [ $score -ge 60 ] && [ $score -le 69 ]
  then
     echo "仅仅及格,你这不点赞收藏? "
  elif [ $score -ge 0 ] && [ $score -le 59 ]
  then
     echo "得到$score分,就这点分还来白嫖?快去一键三连! "
fi
else
 echo " 请正确输入! "

fi

Insert picture description here
Here are the specific input test results:
Insert picture description here

Two, case statement multi-branch structure

(The execution efficiency is faster than if, it directly finds the relevant conditions that are satisfied, and if looking down one by one, it will be slower)
Insert picture description here

General format:

case 变量值 in
模式 1)          #符合模式1时,执行命令1
命令序列 1        #这里是一个具体的命令1
;;               #这里表示命令序列1的结束
模式 2)
命令序列 2
;;
......
*)               #默认其他没有模式的执行
默认命令序列       
esac             #反写case固定格式

Square brackets can be used in the pattern to indicate a continuous range, such as "[ 0-9 ]"


#!/bin/bash
#case测试
read -p "请输入你的ACP成绩(0-100):" score
case $score in

[89][0-9]|100)
  echo "$score,可以通过!"
  ;;
[1-7][0-9])
  echo "$score,同志仍需努力"
  ;;
[0-9])
  echo "$score,同志仍需努力"
  ;;
*)
  echo "请正确输入分数"

esac

Insert picture description here
Insert picture description here

Note: Be sure to pay attention to the use of spaces in shell scripts. For example, don't forget to add spaces in [].

Guess you like

Origin blog.csdn.net/weixin_44324367/article/details/111299842