Shell Script Array Usage Summary _linux shell

Source: Internet
Author: User

Array as a data structure, in some high-level languages are directly provided and implemented, of course, my shell is also some ha.

PS: This article is written because brother B in the group sent a screenshot:

My big B elder brother is still omnipotent talent ha ... Cut the crap and talk about it.

1, how to declare an array variable?

Direct assignment:

Copy Code code as follows:

array[0]= "Zero" array[1]= "one" array[2]= "two"

Declare statement:
Copy Code code as follows:
Declare-a Array

Parenthesis Space Method:
Copy Code code as follows:
Array= (Zero one Two)

Quotation mark Space Method:
Copy Code code as follows:
Array= "Zero One Two"

Mixing method:
Copy Code code as follows:
array= ([0]= "Zero" [1]= "one" [2]= "two")

2, how to traverse an array?

Standard for loop:

Copy Code code as follows:

[Chenqing@qing ~] for ((i=0;i<${#array [@]};i++)) do echo ${array[i]}; Done
Zero
One
Two

For...in:

Copy Code code as follows:

[chenqing@qing ~] for i in ${array[@]};d o echo $i;d one
Zero
One
Two

3, get the length of the array

Copy Code code as follows:

[chenqing@qing ~] echo ${#array [@]}
3
[chenqing@qing ~] echo ${#array [*]}
3

4. Delete array elements

Copy Code code as follows:

[chenqing@qing ~] unset array[0]
[chenqing@qing ~] echo ${#array [@]}
2
[chenqing@qing ~] for i in ${array[@]};d o echo $i;d one
One
Two

5, delete the array

Copy Code code as follows:

unset array

6, like the Python slice

Copy Code code as follows:

[chenqing@qing ~] Echo ${array[@]:0:1}
Zero
[chenqing@qing ~] Echo ${array[@]:0:2}
Zero One
[chenqing@qing ~] Echo ${array[@]:0:3}
Zero One Two
[chenqing@qing ~] Echo ${array[@]:1}
One Two
[chenqing@qing ~] Echo ${array[@]:2}
Two

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.