Conditional control and looping statements for shell scripts

Source: Internet
Author: User
Tags case statement

Conditional judgment: If statement

Syntax format:


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

The IF statement determines which branch to execute by using relational operators to determine whether an expression is true or false. The Shell has three kinds of if ... else statements:

if ... fi 语句 if ... else ... fi 语句 if ... elif ... else ... fi 语句Example:
#!/bin/bash/a=tenb=if [$a = ="A is equal to B  " -" A is greater to B "Else   " a is less to B " fi

The IF ... else statement can also be written as a line and run as a command:

A=; b=; if " A is equal to B "; Else " a is not equal to B "; fi;

The IF ... Else statement is also often used in conjunction with the Test command, as in the above:

#!/bin/bash/a=tenb=if test $a = ="A is equal to B  "else"A is not equal to B"fi

Branching control: Case statements

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


#!/bin/bash/Grade="B" Case$gradeinch"A") echo"Very good!";;"B") echo"good!";;"C") echo"Come on!";;*) echo"You must try!"Echo"sorry!";; Esac

The conversion to the C language is:

#include <stdio.h>intMain () {CharGrade ='B';Switch(grade) { Case 'A': printf ("Very good!"); Break; Case 'B': printf ("Very good!"); Break; Case 'C': printf ("Very good!"); Break;default: printf ("You must try!");p rintf ("sorry!"); Break;}return 0;}

It's easy to understand the comparison. Very similar, but the format is not the same.

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 either a variable or a constant. The matching discovery value conforms to a pattern, in which all commands begin to execute until;;.;; Similar to break in other languages, it means jumping to the end of the entire case statement.

The value will detect each pattern that matches. Once the pattern matches, the other mode is no longer resumed after the corresponding command is executed. If there is no matching pattern, use an asterisk * to capture the value and then execute the subsequent command.

One more example:

#!/bin/bashoption="${1}" Case${option}inch"- F") file="${2}"Echo"File name is $FILE";;"- D") dir="${2}"Echo"Dir name is $DIR";;*) echo"' basename ${0} ': Usage: [-f file] | [-D directory]"Exit1# Command to come outThe program with status1;; Esac

Operation Result:

$./-f filename] | [-D directory]. / is index.html

The special Variable ${1} is used here, referring to the first parameter that gets the command line.

For loop

The shell's for loop differs from the language of C, PHP, and is similar to Python. Here is the syntax format:

For variable in list

do command1 command2 ... commandN doneExample:
#!/bin/bash/for in12345 do  "Thevalue is $value" Done
The value is 1 The value is 2 The value is 3 The value is 4 The value is 5Characters in the sequential output string:
 for inch ' This is a string '  Do Echo $strdone

The code for the polygon will traverse all the files in the current directory. Under Linux, you can change to a different directory to try.

Traversing file contents:


beijingtianjinshanghai#!/bin/bashcitys=' cat city.txt ' for in $ Citysecho $citydone

While loop

As long as the condition behind the while is satisfied, the code block inside the do is executed.

The format is:

While command
Statement (s) to BES executed if command is true

The command finishes, control returns to the top of the loop, and starts from the beginning until the test condition is false.


#!/bin/BASHC=0;  while 3  ]do"Value C was $c"C1' done 


Value C is 0
Value C is 1
Value C is 2

This is because the shell itself does not support arithmetic operations, so 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 just the opposite of the processing mode. The general while loop is better than the until loop, but at some point it is only rare that the until loop is more useful.

The same effect can be achieved by changing the example of the above while loop:

#!/bin/BASHC=03  ]do"Value c is $c " C 1 ' done

First, the statement block in do is running until the until condition is met.


Value C is 0
Value C is 1
Value C is 2

Jump out of the loop

In the loop, sometimes you need to force out of the loop when the loop end condition is not reached, like most programming languages, the shell also uses break and continue to jump out of the loop.


The break command allows you to jump out of all loops (all loops after the execution is terminated).

#!/bin/Bashi=0while5  ]doi1' if 3 ]thenbreak-e $idone

Operation Result:


In a nested loop, the break command can also be followed by an integer that indicates a loop that jumps out of the first layer. For example:

Break n

Indicates a jump out of the nth layer loop.


The continue command is similar to the break command, with only a little difference, and it does not jump out of all loops and just jumps out of the current loop.

#!/bin/Bashi=0while5  ]doi1' if 3 ]thencontinue-e $idone

Operation Result:


The above is a small part of the shell script to introduce the conditions of the control and circular statements related knowledge, I hope to help you!

Conditional control and looping statements for shell scripts

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.