Introduction to shell for loop and Array application

Source: Internet
Author: User

Read a file, assign each row to an array variable, and print it out in a for loop.

Copy codeThe Code is as follows :#! /Bin/sh
I = 1
SUM = 'sed-n' $ = 'tmp.txt '# calculates the total number of lines in the file.
Echo "$ SUM"
While read line
Do
Arr [$ I] = "$ line"
I = 'expr $ I + 1'
Done <tmp.txt
Echo "$ I"
I = 1
For I in 'seq $ Sum'; do
Echo "$ {arr [$ I]}"
Done

Appendix: shell array supplementary knowledge

I. Declare an array

1) array [key] = value # array [0] = one, array [1] = two
2) declare-a array # array is treated as the array name
3) array = (value1 value2 value3 ...)
4) array = ([1] = one [2] = two [3] = three ...)
5) array = "one two three" # echo $ {array [0 | @ | *]}. The array variable is treated as an array, but the array element only contains the string itself.

2. Access the Array

1) $ {array [key] }#$ {array [1]}

3. Delete Arrays

1) unset array [1] # Delete the first element in the array
2) unset array # Delete the entire array

4. Calculate the length of the array

1) $ {# array}
2) $ {# array [0]} # Same as above. $ {# Array [*]} and $ {# array [@]}. Note the difference between # {array: 0} and # {array: 0 }.

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.