Shell for Loop and array application introduction _linux Shell

Source: Internet
Author: User

Reads a file, assigns each row to an array of variables, and prints it out with a for loop

Copy Code code as follows:

#!/bin/sh
I=1
sum= ' sed-n ' $= ' tmp.txt ' #计算文件的总行数
echo "$SUM"
While Read line
Todo
arr[$i]= "$line"
i= ' expr $i + 1 '
Done < Tmp.txt
echo "$i"
I=1
For i in ' seq $SUM ';d o
echo "${arr[$i]}"
Done

Attached: Shell array Supplemental knowledge

An array of declarations

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

Second, access to the array

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

Three, delete the array

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

Calculate the length of the array

1) ${#array}
2) ${#array [0]} #同上. ${#array [*]}, ${#array [@]}. Note the difference between the same #{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.