Shell Loop Statement Usage

Source: Internet
Author: User
Tags arithmetic

Loop statements are often used when writing shell scripts. Here a simple summary of the commonly used 3 kinds of circular statements, so that later can quickly reference to write, nonsense do not say, start Demo:

  1, for

Used mainly for: traversing elements in a known sequence

[Plain] View plaincopy #! /bin/sh-

If [$#-ge 1]; then path=$@ else path=*.sh fi

For I-$path do ls-lh $i The done note: optional in the For loop's in list, and if omitted, the shell traverses the entire command-line argument, at which point for I is equivalent to "$@"

  Give me another example of the usage for:

[Plain] View plaincopy #! /bin/sh-

For i in ' SEQ 1 9 ' does echo $i done Note: For in can and ' with $ ()

Give me another example of the usage for:

[Plain] View plaincopy #! /bin/sh-

For i in {a......z} does echo $i done

  Note:for-in braces {} have automatic completion function, curly braces and to be padded between the contents can not have spaces, to be filled with the contents of the two ... Connected, there should be no spaces and then give a for usage example:

[Plain] View plaincopy #! /bin/sh-

for ((I=1; i<=10; i++))

Do echo $i A done reminder: This is mainly used (())

  2, while

Mainly used for: when a certain condition is established, always carry out

[Plain] View plaincopy #! /bin/sh-

Cnt=9

While [$cnt-ge 0] do echo $ ((cnt--))

Done

Note: 1, arithmetic operations need to be placed in the brackets of $ (())

2, for the arithmetic operation of the variable, in the $ (()), the variable in front does not need $

  3, unitl

Used mainly for: when a condition is set up, stop executing

[Plain] View plaincopy #! /bin/sh-

Cnt=9 until [$cnt-lt 0] do echo $cnt cnt=$ ((cnt-1))

Done

  Note: when assigning a value to a variable, do not add $ to the front

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.