Conditional Statements in "Shell" Programming

1. Condition test operation

1. test command

Test whether the expression is true, if it is true, return 0, otherwise return other values

Format 1: test conditional expression
Format 2: [conditional expression]

2. File test

[operator file or directory]

insert image description here

3. Commonly used test operators
symbol effect
-d Test whether it is a directory (Directory)
-e Test whether a directory or file exists (Exist)
-f Test whether it is a file (File)
-r Test if the current user has 权限读取(Read)
-w Test if the current user 有权限写入(Write)
-x Test if the current user is 有权限执行(excute)
4. Integer value comparison

[ integer1 operator x- integer2 ]
insert image description here

Common test operators:

character effect symbol
-eq Equal to (Equal) ==
- is Not equal to (Not Equal) !=
-gt: Greater Than >
-lt: Less than (Lesser Than) <
-the: Less than or equal to (Lesser or Equal) >=
-ge: greater than or equal to (Greater or Equal) =<

2. Logic test

Format 1: [ expression 1 ] operator[ expression]
Format 2: command 1 operator command 2

(1) Method 1

insert image description here
(2) Method 2

insert image description here
(3) Method 3

insert image description here

Commonly used test operators

  • -a or &&: logic and, "and" means
  • -o or ||: logical or, meaning "or"
  • !: logical no

Three. The structure of the if statement

1. Single branch structure

insert image description here

vim test.sh   //进入脚本编辑
sh test.sh    //进行脚本测试

Enter the script configuration and test

insert image description here

Experiment: Enter an integer to determine whether it is odd or even

首先进入脚本书写:

insert image description here

#! /bin/bash
read -p "请输入一个整数:" num
if [ $(($num%2)) -eq 0 ]
then
  echo "$sum是偶数"
else
  echo "$sum是奇数"
fi

然后进入测试:

insert image description here

2. Double branch structure

insert image description here

Experiment: Prompt the user to enter the number of seconds for the 100-meter race. It is required to judge that the number of seconds is greater than 0 and less than or equal to 10 seconds to enter the trial, and those greater than 10 seconds will be eliminated. If you enter other characters, you will be prompted to re-enter; members who enter the trial will make further judgments Male and female gender, boys enter the boys group, girls enter the girls group, if the input is wrong, please prompt the error

insert image description here

Four. case statement structure

case多分支结构
insert image description here

格式:
case 变量名称 in
模式1)
命令序列
;;
模式2)
程序段
;;
*)
不包含第一个变量内容与第二个变量内容的其他程序执行段
默认程序段
;;
esac
Experiment: Use the case statement to decompress the compressed package named .tar.gz or tar.bz2 according to the suffix to the /opt directory

进入脚本书写:
insert image description here

进行脚本测试看是否能被解压
insert image description here

Guess you like

Origin blog.csdn.net/Wanghwei17/article/details/130415761