Array operations in the shell

Source: Internet
Author: User
Tags array definition array length
1. Array definition, the shell uses a pair of parentheses to represent the array, and the array elements are separated by "spaces"
# empty array arr1
arr1= ()
# array arr2, members are 1, 2, 3, 4, 5, 6
arr2= (1 2 3 4 5 6)
2. Array elements read, format: ${array name [subscript]}, subscript starting from 0, subscript * or @ to represent the entire array content
[Root@10 ~]# Echo ${arr2[0]}
1

[root@10 ~]# echo ${arr2[*]}
1 2 3 4 5 6
3. Traverse Array, foreach
For num in ${arr2[*]}; Do
    echo $num;
Done
4. Array length, Format: ${#数组名 [* or @]}
[Root@10 ~]# echo ${#arr2 [*]}
6
5. Assignment, Format: array name [subscript]= value, if subscript does not exist, new array element;
[Root@10 ~]# arr2[6]=7
[root@10 ~]# echo ${arr2[*]}                    
1 2 3 4 5 6 7
[root@10 ~]# arr2[0]=-1
[root@10 ~]# echo ${arr2[*]}
-1 2 3 4 5 6 7
6. Fragment, Format: ${array name [* or @]: Start bit: length}, intercept part of array, return string, separated by space, and use "()" to get new slice array
[Root@10 ~]# Echo ${arr2[*]:0:3}
-1 2 3
[root@10 ~]# arr3= (${arr2[*]:0:3})
[root@10 ~]# echo ${arr3[*]}
-1 2 3
7. Substitution element, format: ${array name [* or @]/lookup character/substitution character}, does not modify the original array, if you want to modify the array, the result using "()" To assign to the new array
[Root@10 ~]# Echo ${arr2[*]}     
-1 2 3 4 5 6 7
[root@10 ~]# Echo ${ARR2[*]/7/10}
-1 2 3 4 5 6
[root@10 ~]# Arr4= (${ARR2[*]/7/10})
[root@10 ~]# echo ${arr4[*]}
-1 2 3 4 5 6 10
8. Delete array, format: unset array, clear entire array, unset array [subscript], clear individual elements
[Root@10 ~]# Echo ${arr2[*]}
-1 2 3 4 5 6 7
[root@10 ~]# unset arr2[0]
[root@10 ~]# echo ${arr2[*]}
2 3 4 5 6 7

[root@10 ~]# unset arr2
[root@10 ~]# echo ${arr2[*]}

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.