Conditional test operation
File test
- [Operator file or directory]
Commonly used test operators
- -d: test whether it is a directory (Directory)
- -e: Test whether the directory or file exists (Exist)
- f: test whether it is a file (File)
- -r: Test whether the current user has permission to read (Read)
- -w: Test whether the current user has permission to write (Write)
- -x: Test whether the current user has permission to execute (eXcute)
Note: The current user here refers to the user executing the command.
Example:
[ -d /media/cdrom ] && echo $?|| echo $? ###当等式成立输出“0”否则输出“1”
Notes:
- "0": The equation holds
- "1": The equation does not hold
- "&&": logical and, the meaning of "and"
Integer value comparison
- [Integer 1 Operator Integer 2]
Commonly used test operators
- -eq: equal to (Equal)
- -ne: Not Equal
- -gt: Greater Than
- -lt: Less than (Lesser Than)
- -le: Less than or equal to (Lesser or Equal)
- -ge: Greater or Equal
String comparison
- Format 1: [String 1 = String 2]
[String 1! =String 2] - Format 2: [-z string]
Commonly used test operators
- =: The string content is the same
- ! =: The string content is different,! Sign means the opposite
- -z: The string content is empty
Logic test
- Format 1: [Expression 1] Operator [Expression 2]…
- Format 2: Command 1 Operator Command 2…
Commonly used test operators
- -a or &&: logical and, meaning "and"
- -o or ||: logical or, meaning "or"
- ! : Logical no
The structure of the if statement
Single branch structure
if 条件测试操作
then 命令序列
fi
Example:
if [ ! -d $MOUNT_DIR ]
then
mkdir -p $MOUNT_DIR
fi
Double branch structure
if 条件测试操作
then 命令序列1
else 命令序列2
fi
Example:
ping -c 3 -i 0.2 -W 3 $1 &>/dev/null
if [ $? -eq 0 ]
then
echo "Host $1 is up."
else
echo "Host $1 is down."
fi
Multi-branch structure
if 条件测试操作1
then 命令序列1
elif 条件测试操作2
then命令序列2
else
命令序列3
fi
Example
read -p "请输入你的分数(0-100):" A
if [ $A -ge 85 ] && [ $A -le 100 ]
then
echo "$A 分,优秀,继续保持!!"
elif [ $A -ge 70 ] && [ $A -le 84 ]
then
echo "$A 分,合格,仍需加油!“
elif [ $A -ge 0 ] && [ $A -le 69 ]
then
echo "$A 分,不合格,需要加强啦!"
else
echo "$A 分,再乱输,嘶啦嘶啦滴!!!"
fi
case statement structure
case multi-branch structure
case 变量值 in
模式1)
命令序列1
;;
模式2)
命令序列2
;;
......
*)
默认命令序列
esac
Example:
read -p ”请输入一个字符,并按Enter键确认:“KEY
case ”$KEY“ in
[a-z]|[A-Z])
echo "你输入的是字母"
;;
[0-9])
echo "你输入的是数字"
;;
*)
echo "你输入的是空格、功能键或其他控制字符"
esac
to sum up:
Conditional test syntax
- File test, integer value comparison, string comparison, logic test
Syntax of if conditional statement
- Single branch, double branch, multiple branch
Syntax of case multi-branch statement