Shell script Programming Loop statement _linux Shell

Source: Internet
Author: User
Tags numeric value

It is common to repeat a series of commands while running a script, when we need to use a loop statement to do this.

One, for command

Format: for variable in list;

Circulation body

Done

The for command traverses each value in the list and exits the loop after the traversal completes.

The list is in the following ways:

1. A series of values defined in the order;
2, variable;
3, order;
4, catalogue;
5, documents.

Example 1:

The previous example uses the {initial value ... End value} format to represent the numeric value of an interval.

Example 2: Take a variable as a list:


Example 3: Generate a list with commands:


In the example above, the SEQ command is used to generate the list, and the SEQ command is in the format: SEQ [initial value step] end value

Using inverted quotes in the above two examples will result in a command run.

Example 4: Use a directory as a list:

Second, C language style for command

Format: for ((variable assignment; cyclic termination condition; step size); Todo

Circulation body

Done

Example: Ask for the plus from 1 to 100:

Iii. until order

Format: Until condition; Todo

Statement
...
Done

The loop is exited when the condition in the until command is met.

Instance:

Four, while command

Format: While condition; Todo

Statement
...
Done

The while command enters the loop when the condition is satisfied.

Instance:


V. Control cycle

1. Break command

Function: Exit the loop in progress.

Instance: If the variable i is 3, exit the loop.


2, Continue command

Function: Advance into the next round of circulation.
Instance: Adds the number between 1 to 20 and 51 to 100:

Vi. the use of while

1, Dead Cycle

Format: while:; Todo
Statement
Done

Instance:

2. Read the contents of the file into the loop

Format: while read variable name; Todo

Circulation body

Done < documents

Instance: reads the contents of the/etc/passwd file line by row:

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: info-contact@alibabacloud.com 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.