The difference between an array and a variable
Variables: Storing the memory space of a single element
Array: A contiguous memory space that stores multiple elements, equivalent to a collection of multiple variables
Array = array name + index
Index: Numbering starting from 0, which is a numeric index
Note: Indexes can support the use of custom formats, not just numeric formats, which are associated with indexes, which are supported after the bash4.0 version
The array of Bash supports sparse format (index discontinuity)
Defining arrays
Declare-a array_name: Normal array
Declare-a array_name: Associative array
Assignment of array elements:
(1) Assign only one element at a time;
Array_name[index]=value
weekdays[0]= "Sunday"
Weekdays[4]= "Thursday"
(2) Assign all elements at once:
Array_name= ("VAL1" "VAL2" "VAL3" ...)
(3) Assign only specific elements:
Array_name= ([0]= "VAL1" [3]= "VAL2" ...)
(4) Interactive array assignment (only for normal arrays)
Read-a ARRAY
referencing arrays
Referencing an array element: ${array_name[index]}
Note: Omitting [INDEX] means referencing an element with subscript 0
The length of the array (the number of elements in the array):
${#ARRAY_NAME [*]}
${#ARRAY_NAME [@]}
Array Data processing
To reference an element in an array:
All elements: ${array[*]},${array[@]}
Array slice: ${array[@]:offset:number}
Offset: Number of elements to skip
Number: How many elements to remove
Take all elements after offset: ${array[@]:offset}
Append an element to an array: array[${#ARRAY [*]}]
Deleting an element in an array will form a sparse format: unset Array[index]
Associative array: declare-a array_name
Array_name= ([idx_name1]= ' val1 ' [idx_name2]= ' val2 ' ...)
Application examples
1, save 10 random numbers using an array, and find out the maximum and minimum values
Example code:
[email protected] array]# cat arrayrandom.sh
#!/bin/bash
#Author: Wangjun
#Contact qq:183530300
#Version: 2.0
#Create time:2016-08-23 10:33:38
#Description: Compares the size of the random number stored in array
Declare-a Array_random
Declare-i maxrandom=0
Declare-i minrandom=32767
For I in {0..9};d o
array_random[$I]=$[random]
echo ${array_random[$I]}
if [[${array_random[$I]}-gt $maxrandom]];then
maxrandom=${array_random[$I]}
elif [[${array_random[$I]}-lt $minrandom]];then
minrandom=${array_random[$I]}
Fi
Done
Echo Maxrandom is: $maxrandom
Echo Minrandom is: $minrandom
[Email protected] array]# arrayrandom.sh
31892
30901
16560
226
7987
2082
5756
23992
28530
21832
Maxrandom is:31892
Minrandom is:226
This article is from the "Love Firewall" blog, be sure to keep this source http://183530300.blog.51cto.com/894387/1841450
Shell script Programming-arrays (array)