Shell script conditional statement and the use of if statement

1. Condition test

  • If you want to make the Shell script program have a certain "intelligence", the first question is how to distinguish between different situations to perform what kind of operation
  • The Shell environment judges whether the execution is successful according to the return value status ($?) after the command is executed. When the return value is 0, it means success, otherwise a non-zero value means failure.

1.1 test command

  • The specific condition expression can be tested, and the return value is 0 to indicate that it is true.
基本格式:
 test   条件表达式
 [ 条件表达式 ]
  • These two functions are exactly the same, the latter is more commonly used and closer to programming habits. Note: At least one space separates the latter square bracket and the conditional expression.

1.1.1 File testing

  • According to the given path name, determine whether it corresponds to a file or a directory, or whether the file is readable, writable, executable, etc.
  • Common operation options
-d:测试是否为目录(Directory)
-e:测试目录或文件是否存在(Exit)
-f:测试是否为文件(File)
-r:测试当前用户是否有权限读取(Read)
-w:测试当前用户是否有权限写入(Write)
-x:测试是否设置有可执行(Excute)权限

Example:

[root@localhost ~]# [ -d /dev/sr0 ]
[root@localhost ~]# echo $?
1
[root@localhost ~]# [ -e /dev/sr0 ]
[root@localhost ~]# echo $?
0
[root@localhost ~]# [ -e /dev/cdrom ]&& echo "YES"       ## 文件是否为目录,是的话输出YES
YES

1.1.2 Judging between files

  • To compare the two files, the commonly used options are:
-nt:判断文件A是否比文件B新
-ot:判断文件A是否比文件B旧
-ef:判断两个文件是否为同一个文件,用来判断两个文件是否指向同一个inode

Example:

[root@localhost ~]# touch a
[root@localhost ~]# touch b
[root@localhost ~]# [ a -ot b ]&& echo "YES" || echo "NO"   ## a是否比b文件旧
YES
[root@localhost ~]# [ a -nt b ]&& echo "YES" || echo "NO"  ## a是否比b文件新
NO
[root@localhost ~]# ln a c  ## 创建a文件的硬连接c
[root@localhost ~]# [ a -ef c ]&& echo "YES" || echo "NO"  
YES                ## 指向同一个inode

Two, integer value comparison

  • According to the given two integer values, determine the relationship between the first number and the second number, such as whether it is greater than, equal to, or less than the second number.
  • Common options are as follows:
-eq: 第一个数等于(Equal)第二个数
-ne:第一个数不等于(Not Equal)第二个数
-gt:第一个大于(Greater Than)第二个数
-lt:第一个数小于(Lesser Than)第二个数
-le:第一个数小于或等于(Lesser or Equal)第二个数
-ge:第一个数大于或等于(Greater or Equal)第二个数
  • Integer value comparison is often used in Shell scripting. It can be used to determine the number of logged-in users, the number of open processes, and whether the disk usage is up to standard.
[root@localhost ~]# unum=`who | wc -l`
[root@localhost ~]# [ $unum -gt 5 ]&& echo "litter"|| echo "Too many"
litter                      ## 查看登录的用户数量,大于等于5个发出Too many 的报警

Three, string comparison

  • String comparison is usually used to check whether user input, system environment, etc. meet conditions. In Shell scripts that provide interactive operations, it can be used to determine whether the positional parameters input by the user meet the requirements.
  • Common options are as follows
=: 第一个字符串与第二个字符串相同=:第一个字符串与第二个字符串不相同,其中“!”符号表示取反
-z:检查字符串是否(Zero),对于未定义或赋予空值的变量将视为空串。

Example:

[root@localhost ~]# echo $LANG  ## 查看当前语言环境
zh_CN.UTF-8
[root@localhost ~]# [ $LANG != "en.US" ]&& echo  "Not en.US"  ## 字符串测试结果 (不等于)
Not en.US

Four, logic test

  • Logic testing refers to judging the dependency between two or more conditions. When the system task depends on multiple different conditions, a test process is needed to determine whether these conditions are established at the same time or as long as one of them is established.
symbol meaning
&& Logical AND means "and", and only when both conditions are true, the return value of the entire test command is 0 (the result is true). When using the Test command, "&&" can be changed to "-a"
|| Logical OR means "or". As long as one of the two commands before and after is established, the return value of the entire test command is 0 (the result is established). When using the Test command, "||" can be changed to "-o"
! Logic negative means "no". Only when the specified condition is not established, the return value of the entire test command is 0 (the result is established).

Five, if statement

In Shell script applications, the most commonly used flow control method for if statements is used to perform different operations (if... then...) according to the test results of specific conditions.

  • According to different levels of complexity, the selection structure of if statements can be divided into three basic types, suitable for different applications

5.1 Single branch if statement

  • The "branch" of the if statement refers to the execution statements (one or more) corresponding to different test results. For the branch selection structure, the corresponding code will only be executed when the "condition is met", otherwise no operation will be performed.
if 条件测试操作
then 
	命令序列
fi
  • flow chart
    Insert picture description here

5.2 Double-branch if statement

  • The dual-branch selection structure requires different operations to be performed for the two situations of "conditions are met" and "conditions are not met".
if 条件测试操作
then
命令序列 1
else
命令序列 2
fi
  • flow chart
    Insert picture description here

5.3 Multi-branch if statement

  • Since the if statement can perform operations based on whether the test result is true or not, it can be nested and used for multiple judgments.
  • The nesting of if statements is not commonly used when writing Shell scripts, because multiple nesting easily makes the program structure more complicated.
  • The basic format is as follows
if 条件测试语句 1
then
命令序列 1
elif 条件测试语句 2
then 
	命令序列 2
else
	命令序列 3
fi

  • flow chart
    Insert picture description here

5.3 Application of if multi-branch statement

  • Guess the box, use the enumeration method to use if multiple branch statements
#! /bin/bash
 read -p "请输入您的出拳手势 其中  0代表拳头 1代表剪刀 2代表布 "  A
        B=$[$RANDOM%3]
if [ $A -ge 0 ]&&[ $A -le 2 ]
 then
  if [ $A -eq 0 ]
then
    if [ $B -eq 0 ]
then
        echo "您出的是拳头"
        echo "电脑出的也是拳头"
        echo "这局是平局"
elif [ $B -eq 1 ]
then
        echo "您出的是拳头"
        echo "电脑出的是剪刀"
        echo "您赢了!"
else
        echo "您出的是拳头"
        echo "电脑出的是布"
        echo "您输了,电脑赢了!"
fi
  elif [ $A -eq 1 ]
then
    if [ $B -eq 0 ]
then
        echo "您出的是剪刀"
        echo "电脑出的是拳头"
        echo "您输了,电脑赢了"
    elif [ $B -eq 1 ]
 then
        echo "您出的是剪刀"
        echo "电脑出的也是剪刀"
        echo "这局是平局"
else
        echo "您出的是剪刀"
        echo "电脑出的是布"
        echo "您赢了!"
fi
  elif [ $A -eq 2 ]
then
      if [ $B -eq 0 ]
then
         echo "您出的是布"
         echo "电脑出的是拳头"
         echo "您赢了"
     elif [ $B -eq 1 ]
 then
         echo "您出的是布"
         echo "电脑出的是剪刀"
         echo "您输了,电脑赢了"
 else
         echo "您出的是布"
         echo "电脑出的也是布"
         echo "这局是平局"
fi
else
        echo ""
fi
else
        echo "请输入正确的数字"
fi
          

Guess you like

Origin blog.csdn.net/weixin_47219725/article/details/107403294