Conditional statement of shell basic teaching

One, if statement

The use of if statement needs to judge multiple different conditions

1.1 Single branch statement

  • The if single-branch statement is to perform an operation when a certain condition is met, but do not perform any operation when the condition is not met
  • structure:
    Insert picture description here
基本格式:
if 条件测试操作
    then  命令序列
fi

Example:
:
Insert picture description here

1.2 Double branch statement

  • An if double-branch statement is to perform an operation when a certain condition is met, and perform another operation when this condition is not met
  • structure:
    Insert picture description here
基本格式:
if 条件测试操作
	then  命令序列1
	else  命令序列2
fi

Example:
Insert picture description here
Insert picture description here

1.3 Multiple branch statements

  • The if multi-branch statement is to execute command 1
    when condition 1 is met ; ——>when condition 1 is not satisfied, go down to judge whether condition 2 is satisfied, if condition 2 is satisfied, execute command 2;
    ——>if not satisfied Condition 2, then continue to go down until the else statement, indicating that the previous conditions are not met, and finally execute the command n
  • structure:
    Insert picture description here
基本格式:
if 条件测试操作1
	then  命令序列1
elif  条件测试操作2
	then  命令序列2
	... ...
else
	命令序列3
fi

Example:
Insert picture description here
Insert picture description here

Two, case branch statement

  • The case statement is mainly used in the following scenarios: when there are multiple values ​​for each variable, a different sequence of commands needs to be executed for each value
  • The if statement is to judge multiple different conditions, and case judges the different values ​​of a variable
  • structure:
    Insert picture description here
基本格式:
case 变量值 in
模式1)
	命令序列1
	;;
模式2)
	命令序列2
	;;
	....
*)
	默认命令序列
esac
  • The end of the case line must be the word in, and each line must end with brackets ")"
  • The double semicolon ";;" indicates the end of the command sequence
  • You can use square brackets "[]" to indicate a continuous range, such as "[ 0-9 ]"; you can also use "|" to indicate, such as" A|B "
  • The last ")*" means the default mode. If the above values ​​are not the same, then execute this line
    Example:Insert picture description here
    Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_51613313/article/details/111305552