Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use conditional Control and Loop statements in Shell script

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the Shell script condition control and loop statement how to use, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor with you to understand.

Conditional judgment: if statement

Syntax format:

If [expression] thenStatement (s) to be executed if expression is truefi

Note: there must be a space between expression and square brackets ([]), otherwise there will be syntax errors.

The if statement determines which branch to execute by determining whether the expression is true or false by the relational operator. There are three kinds of if for Shell. Else statement:

If... Fi statement if... Else... Fi statement if... Elif... Else... Fi statement

Example:

#! / bin/bash/a=10b=20if [$a = = $b] thenecho "an is equal to b" elif [$a-gt $b] thenecho "an is greater to b" elseecho "an is less to b" fi

If... The else statement can also be written on one line and run as a command:

Then echo "an is equal to b"; else echo "an is not equal to b"; if [$a = = $b]

If... The else statement is also often used in conjunction with the test command to do the same thing as above:

#! / bin/bash/a=10b=20if test $a = = $b then echo "an is equal to b" elseecho "an is not equal to b" fi

Branch control: case statement

Case... Esac and switch in other languages. The case statement is similar to a multi-branch selection structure.

Example:

#! / bin/bash/grade= "B" case $grade in "A") echo "Very Good!";; "B") echo "Good!";; "C") echo "Come On!"; *) echo "You Must Try!" echo "Sorry!"; esac

The conversion to C language is:

# include int main () {char grade = 'switching switch (grade) {case'Aging: printf ("Very Good!"); break;case 'Bounding: printf ("Very Good!"); break;case 'Clearing: printf ("Very Good!"); break;default: printf ("You Must Try!"); printf ("Sorry!"); break;} return 0;}

By comparison, it's easy to understand. It's very similar, but the format is different.

It is important to note that:

The value must be followed by the keyword in, and each pattern must end with a closing parenthesis. The value can be a variable or a constant. After the match discovers that the value matches a certain pattern, all commands begin to execute until;;. Similar to break in other languages, it means to skip to the end of the entire case statement.

The value detects each pattern that matches. Once the pattern matches, the corresponding command to match the pattern is executed and the other patterns are not continued. If there is no matching pattern, use the asterisk * to capture the value, and then execute the following command.

Let me give you another example:

#! / bin/bashoption= "${1}" case ${option} in "- f") FILE= "${2}" echo "File name is $FILE"; "- d") DIR= "${2}" echo "Dir name is $DIR";; *) echo "`basename ${0} `: usage: [- f file] | [- d directory]" exit 1 # Command to come out of the program with status 1esac

Running result:

$. / test.shtest.sh: usage: [- f filename] | [- d directory]. / test.sh-f index.htmlFile name is index.html

The special variable ${1} is used here, which refers to getting the first argument on the command line.

For cycle

Shell's for loop is different from c, php and other languages, and is very similar to Python. The following is the syntax format:

For variable in list

Docommand1command2...commandNdone

Example:

#! / bin/bash/for value in 1 2 3 4 5do echo "The value is $value" done

Output:

The value is 1The value is 2The value is 3The value is 4The value is 5

Sequentially output characters in a string:

For strin 'This is a string'doecho $strdone

Running result:

This is a string

Traverse the files in the directory:

#! / bin/bashfor FILE in * doecho $FILEdone

The above code will traverse all the files in the current directory. Under Linux, you can try changing it to another directory.

Traverse the contents of the file:

City.txt

Beijingtianjinshanghaihammer city in bincitys = `cat city.txt`for city in $Bash $citydone

Output:

Beijing

Tianjin

Shanghai

While cycle

The block of code in the while is executed as long as the conditions behind the do are met.

Its format is:

While command

Do

Statement (s) to be executed if command is true

Done

After the command is executed, the control returns to the top of the loop, starting from scratch until the test condition is false.

Example:

#! / bin/bashc=0;while [$c-lt 3] doecho "Value c is $c" c = `expr $c + 1`done

Output:

Value c is 0

Value c is 1

Value c is 2

Here, since shell itself does not support arithmetic, use the expr command for self-increment.

Until cycle

The until loop executes a series of commands until the condition is true. The until loop and the while loop are handled in the opposite way. While loops are generally better than until loops, but in some cases, and only in rare cases, until loops are more useful.

Change the example of the while loop above to achieve the same effect:

#! / bin/bashc=0;until [$c-eq 3] doecho "Value c is $c" c = `expr $c + 1`done

First of all, the statement block in do runs until the condition of until is met.

Output:

Value c is 0

Value c is 1

Value c is 2

Jump out of the cycle

During a loop, it is sometimes necessary to force a jump out of the loop when the end condition of the loop is not met, and like most programming languages, Shell uses break and continue to jump out of the loop.

Break

The break command allows you to jump out of all loops (terminating execution of all subsequent loops).

#! / bin/bashi=0while [$I-lt 5] doi= `expr $I + 1`if [$I = = 3] thenbreakfiecho-e $idone

Running result:

one

two

In a nested loop, the break command can be followed by an integer to indicate which layer of the loop to jump out of. For example:

Break n

Means to jump out of the layer n loop.

Continue

The continue command is similar to the break command, except that it does not jump out of all loops, just out of the current loop.

#! / bin/bashi=0while [$I-lt 5] doi= `expr $I + 1`if [$I = = 3] thencontinuefiecho-e $idone

Running result:

one

two

four

five

Thank you for reading this article carefully. I hope the article "how to use conditional Control and Loop sentences in Shell script" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report