Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Shell script if else statements

Shulou Source: shulou.com Published: 2022-06-03 08:22:13 11月14日 Update

This article mainly introduces "how to use Shell script if else statements". In daily operation, I believe many people have doubts about how to use Shell script if else statements. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use Shell script if else statements". Next, please follow the editor to study!

Unlike Java, PHP and other languages, the process control of sh cannot be empty, such as:

The code is as follows:

You can't write this in sh/bash. If the else branch doesn't have a statement to execute, don't write the else, like this:

The code is as follows:

If condition

Then

Command1

Command2

...

CommandN

Fi

Of course, it can also be written as a line (for terminal command prompts), like this:

The code is as follows:

If test $[2: 3]-eq $[1: 5]; then echo 'The two numbers are equalizer; fi

The fi at the end is if, which is spelled upside down, and you'll encounter something similar later.

If else format

The code is as follows:

If condition

Then

Command1

Command2

...

CommandN

Else

Command

Fi

If else-if else format

The code is as follows:

If condition1

Then

Command1

Elif condition2

Command2

Else

CommandN

Fi

If else statements are often used in conjunction with the test command, as follows:

The code is as follows:

Num1=$ [2x3]

Num2=$ [1x 5]

If test $[num1]-eq $[num2]

Then

Echo 'The two numbers are equalizer'

Else

Echo 'The two numbers are not equalizer'

Fi

Output:

The two numbers are equal!

At this point, the study on "how to use Shell script if else statements" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Statements code scripts learning commands more formatting help utility no then one line branch that is prompt article method end flow theory Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS OPPO Reno NVidia Huawei Shulou Information