Array:
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 name and 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)
Declaring an array: declare-a array_name: normal array (declaration optional)
Declare-a array_name: Associative array ( must be declared before available )
Note : The two cannot be converted to each other
Array Assignment
Single assignment: weekdays[0]= "Sunday"
Multiple assignments: name= ("Mage" "Zhangsir" "Wang")
Specific element assignment: title= ([0]= "yuan[3]")
Interactive assignment: Read-a
Show all arrays: declare-a
referencing arrays
Referencing an array element: ${array_name[index]}
Note: Omitting [INDEX] means referencing an element with subscript 0
Referencing all elements of an array:
${array_name[*]} ${array_name[@]}
The length of the array (the number of elements in the array):
${#ARRAY_NAME [*]}
${#ARRAY_NAME [@]}
Delete an element in an array: Causes sparse format unset Array[index]
Delete entire array: unset array
Array Data processing
To reference an element in an array:
Array slice: ${array[@]:offset:number}
Offset: Number of elements to skip
Number: How many elements to remove
All elements after the offset ${array[@]:offset}
Append an element to the array:
array[${#ARRAY [*]}]=value
Associative arrays:
Declare-a array_name array_name= ([idx_name1]= ' val1 ' [idx_name2]= ' val2 ' ...)
Note: Associative arrays must be declared before they are called
Example
Generates 10 random numbers stored in an array and finds its maximum and minimum values
#! /bin/bash
DECLARE-a Rand for((i=0;i<Ten; i++)); Dorand[$i]=$RANDOMif[$i-eq0];then Max=${rand[$i]} min=$maxElse[$max-lt ${rand[$i]}] && {max=${rand[$i]};Continue; } [$min-GT ${rand}[$i]] && min=${rand[$i]} Fidoneecho all Rand is${rand[*]}echo Max Rand is$maxecho Min Rand is$min
Write a script that defines an array in which the elements are all in the/var/log directory. Log at the end of the file, the sum of the rows of the file whose subscript is an even number is counted.
#!/bin/-a filesfiles= (/var/log/*. log) Declare-i lines=0for i in $ (seq 0 $[${# Files[*]}-1]); do if [$[$i%2]-eq 0];then let lines+=$ (Wc-l ${files[$i]} | cut-d "-f1) Fidoneecho" lines: $lines.
Shell Script Programming arrays