当前位置:网站首页>Fundamentals of shell programming (Part 7: branch statement -if)
Fundamentals of shell programming (Part 7: branch statement -if)
2022-06-22 22:20:00 【Just call me Wang Yuanwai】
Preface
In the execution stream , Execute different statements according to conditions , Branch statement , stay shell Programming , Mainly if、case in Use , Let's study together
if sentence
1、 Need semicolons to separate
if true;then
echo hello world
fibecause true The exit status code of the command is 0, So included in then And fi Statements between will execute
2、 No semicolons are required to separate
if true
then
echo hello world
fibecause true And then Not in the same line , therefore ; It can be omitted , Which of the two formats is used , It's the same with all of them
if-else sentence
1、 Need semicolons to separate
if true; then
echo hello world
else
echo what
fibecause true The exit status code of is always 0, therefore else And fi Statements Between cannot be executed
2、 No semicolons are required to separate
if true
then
echo hello world
else
echo what
fibecause then And true Not in the same line , No need to use ; separate
if-elif sentence
1、 Need semicolons to separate
if false; then
echo what
elif true; then
echo hello world
fibecause false The exit status code of the command is fixed as 1, therefore if The code in the statement will not execute , Turn to judgment elif Exit status code in
2、 No semicolons are required to separate
if false
then
echo what
elif true
then
echo hello world
fibecause false And then、true And then Are not on the same line , So you can omit ; separate
if-elif-else sentence
1、 The same line should be separated by semicolons
if true; then
echo hello world
elif false; then
echo what
else
echo haha
fibecause true The exit status code of is 0, therefore if The statements in execute ,elif、else The statements in will not have a chance to be OK
2、 No semicolons are required to separate
if true
then
echo hello world
elif false
echo what
else
echo haha
fiThe characteristics of conditional statements
if true; then
echo hello world
elif false; then
echo what
else
echo haha
fiOnce a qualified statement is executed , Other statements will not execute
if Rule of judgement
if true; then
echo hello world
fiBe careful :
1、if Statement only determines the exit status code , There is no... In other languages boolean value ,true It's also an order , because true The exit status code of is always 0, So the condition is always true !
2、 Any order , As long as there is an exit status code, it can be placed in if perhaps elif As a condition , However, a common condition command is test
Common conditional commands test
1、 Judging the equality of strings
if test "a" = "a"; then
echo hello world
fibecause a And a equal , therefore test The exit status code of the command is 0, here then And fi Statements between will be executed
2、 Judge that the file exists
if test -f "hello.txt"; then
echo hello world
fi-f And "hello.text" Are passed to test Arguments to the command , Therefore, the principle of word separation should be strictly implemented , Use white space characters to separate
3、test There are many other ways to judge commands , Do you think test tedious ??? So the author provides test Shorthand for commands
test Shorthand for commands []
1、 Judging the equality of strings
if [ "a" = "a" ];then
echo hello world
fibecause [] by test Shorthand for commands , therefore [] The space between characters cannot be omitted , Represents separation test Commands and parameters
2、 Judge whether the file exists
if [ -f "hello.txt" ]; then
echo hello world
fi3、 More conditional judgments ( String judgment )
- [ string ]: Judge string Not empty
- [ -n string ]: Judge string Length greater than zero
- [ -z string ]: Judge string The length is zero
- [ string1 = string2 ]: Judge string1 and string2 Are they the same?
- [ string1 == string2 ] : And [ string1 = string2 ] equally
- [ string1 != string2 ]: Judge string1 And string2 Is it different
- [ string1 '>' string2 ]: In dictionary order string1 Whether in string2 after
- [ string1 '<' string2 ]: In dictionary order string1 Arrange in string2 Before
When the condition is true ,test The exit status code of the command is 0
4、 More conditional judgments ( File to judge )
- [ -a file ]:file There is
- [ -d file ]:file Exists and is a directory
- [ -e file ]: If file Exists and is an executable
- [ -f file ]: If file It exists and is a normal file
………… There are still a lot of it
5、 More conditional judgments ( Integer judgment )
- [ integer1 -eq integer2 ]:integer1 be equal to integer2
- [ integer1 -ne integer2 ]:integer1 It's not equal to integer2
- [ integer1 -le integer2 ]:teger1 Less than or equal to integer2
- [ integer1 -lt integer2 ]:integer1 Less than integer2
- [ integer1 -ge integer2 ]:integer1 Greater than or equal to integer2
- [ integer1 -gt integer2 ]:integer1 Greater than integer2
When the judgment condition is true ,test The command will return the exit status code 0
test Another shorthand for commands [[]]
1、 Judging the equality of strings
if [[ "a" = "a" ]]; then
echo hello world
fi2、 Judge whether the file exists
if [[ -f "hello.txt" ]]; then
echo hello world
fi3、 And [] The difference between , regular expression
[[ string1 =~ regex ]]
regex A regular expression ,=~ It's a regular comparison operator
if Write in a single line
if true; then echo hello world;fiUse ; Just separate
Alternative usage : Write multiple commands
if false; true; then
echo hello world
fifalse Command and true The orders are written in if Behind , here if Only the exit status code of the last command will be judged
Conditions and &&
if [ a = a ] && [ b = b ]; then
echo hello world
fiJudge multiple commands , When the exit status code of all commands is 0 when , Will execute then And fi The statement in
Condition or ||
if [ a = b ] || [ c = c ] ;then
echo hello world
fiJudge multiple commands , When the exit status code of any command is 0 when , Will execute then And fi The sentence between
Skillfully use conditions to execute statements
$ command1 && command2
Execute first command1, Only command1 Successful implementation ( Exit status code is 0) after , To perform command2
$ command1 || command2
Execute first command1, Only command1 Execution failure ( Exit status code is not 0) after , To perform command2summary
1、shell Programming if The statement does not check boolean value , It only judges the exit status code
2、 As long as there is a command with exit status code , Include built-in commands 、 Executable program 、 function , Can be used as if Later conditions
3、shell The reason why programming is difficult to learn is : Too much code ……
边栏推荐
- Is data scientist a promising profession?
- [mavros] mavros startup Guide
- 6-3 non recursive traversal of binary tree
- Rapideye, spot satellite remote sensing image data
- Solve the problem that MySQL in phpstudy cannot be started and conflicts with locally installed MySQL
- Lesson 026: Dictionary: when the index is not easy to use 2 | after class test questions and answers
- ≥ server2012r2 system, disable some planned tasks of the system
- Cannot re register id: pommeffacompetition-v0 problem solving
- CSV add a new column
- Redis distributed lock
猜你喜欢

Database summary: common problems and Optimization in MySQL development

【李沐】 如何读论文【论文精读】
![[path planning] week 1: hodgepodge](/img/8b/d7c370b0deac33c41a72f8105ea357.png)
[path planning] week 1: hodgepodge
![[recommended by Zhihu knowledge master] castle in UAV - focusing on the application of UAV in different technical fields](/img/3b/8916c543c149292221ce500209df0d.png)
[recommended by Zhihu knowledge master] castle in UAV - focusing on the application of UAV in different technical fields

The necessary materials for the soft test have been released. All the soft test materials for the whole subject have been prepared for you!

Implementation of depth traversal adjacency matrix of figure 6-5
![下一个排列[发挥主观能动性发现规律]](/img/bb/262e1a21e4babb8d221d737ced3bcc.png)
下一个排列[发挥主观能动性发现规律]

Las point cloud create mesh
![[ongoing update...] 2021 National Electronic Design Competition for college students (III) interpretation of the anonymous four axis space developer flight control system design](/img/5d/71c75a3622f7814f385d04b6148074.png)
[ongoing update...] 2021 National Electronic Design Competition for college students (III) interpretation of the anonymous four axis space developer flight control system design
![[geometric vision] 4.2 piecewise linear transformation](/img/1e/a810f4d7e9a6a34647b5cb56fdde67.png)
[geometric vision] 4.2 piecewise linear transformation
随机推荐
RuntimeError: CUDA error: CUBLAS_ STATUS_ EXECUTION_ FAILED when calling `cublasSgemmStridedBatched( ha
【MAVROS】MAVROS 啓動指南
SPA项目开发之登录注册
Lesson 030: file system: introduce a big thing | after class test questions and answers
勒索病毒横行下设备该如何进行加密防护
TC397 Flash
Makefile:1860: recipe for target ‘cmake_check_build_system‘ failed make: *** [cmake_check_build_syst
【持续更新中...】2021年全国大学生电子设计大赛 (三)匿名四轴拓空者飞控系统设计解读
volume rendering
Eureka服务注册与发现
322.零钱兑换
Campus errand management app Shaanxi Gechuang
【象棋人生】01 人生如棋
Implementation of depth traversal adjacency matrix of figure 6-5
6-1 operation set of binary search tree
5分钟快速上线Web应用和API(Vercel)
Task management of embedded development foundation (thread management)
CVPR2022 | 用于重采图像的特征解耦学习与动态融合
组合总数[标准回溯 + 回溯技巧--降低栈深度]
pycharm 配置远程连接服务器开发环境