Shell learning notes and shell scripts

Source: Internet
Author: User

Shell learning notes and shell scripts
1. for Loop 1. Syntax format 1

For variable in value 1 value 2 value 3... do program done

 Note: The program will traverse all values, assign values to variables, and then execute the program. That is to say, the number of subsequent values will be the number of times the program loops.

2. Example 1: traverse 5 numbers for output
#! /Bin/bashfor I in 1 2 3 4 5do echo $ idone # output result 12345

3. Example 2: traverse all files in the directory and output the file name

#! /Bin/bashfor file in $ (ls) # Note: ls will list all the files in the current directory and assign values to the files one by one. Then do echo $ filedone can be output one by one.

 

4. Syntax Format 2
For (initial value; cyclic control condition; variable change) do program done

 

Note: This format is the same as that of the C for loop. The difference is that the loop conditions must be enclosed in double brackets.

5. Example 1: Calculate the sum of 1 to 100.
#! /Bin/bashsum = 0for (I = 1; I <= 100; I = I + 1) do sum = $ ($ sum + $ I )) # It can also be used, sum = $ [$ sum + $ I] doneecho $ sum # output 5050

 

Ii. while loop 1. Syntax format
While [conditional statement] do program done

 

Note: When the conditional statement is set to true, the program will be executed until the conditional statement fails to exit the loop.

2. Example: Calculate the sum from 1 to 100
#! /Bin/bashi = 1sum = 0 while [$ I-le 100] do sum = $ (sum + I) I = $ (I + 1 )) doneecho $ sum # output 5050

 

Iii. until loop 1. Syntax format
Until [conditional statement] do program done

 

Note: The until loop is the opposite of the while loop. When the conditional statement is invalid, the program will be executed until the conditional statement is set up to exit the loop.

2. Example: Calculate the sum from 1 to 100
#! /Bin/bashi = 1sum = 0 until [$ I-gt 100] do sum = $ (sum + I) I = $ (I + 1 )) doneecho $ sum # output result 5050

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.