Q1. Arrays
We know that variables are memory space, each variable can only store a single data, a one-time assignment operation, then encountered some need to continuously store and read the task, if you still rely on the variable for multiple storage, will not guarantee the memory space continuity, and greatly reduce the efficiency of the CPU, This is the type of variable that needs to be an array!
Array variables:
An array is simply a contiguous memory space that holds one or more elements, equivalent to a set of multiple variables;
The index of an array has the following methods:
1. Digital Index. Called an indexed array of index arrays;
0,1,2,3 ....
2. Name (string): called associative array related array;
bash4.0 more than version support
Arrays are divided into two types: dense arrays and sparse arrays
Dense arrays: Index numbers must be contiguous, similar to sequential functions ordered sequentially, without breakpoints;
Sparse array: The index number can be discontinuous, the bash array belongs to the sparse array;
Methods for declaring arrays:
1. Before the declare command, you can declare a variable.
-I NAME declares an integer variable
-X NAME declares environment variable
Similarly, you can declare an array variable with it
-A: Declaring an indexed array (if supported)
-A: declaring associative arrays (if supported)
2. Declaring an array directly
Assign a value directly to an array:
Array_name= ("value1" "value2" ...) Dense array
Array_name= ([0]= "value1" [5]= "value2" ...) Sparse array
3. Create an array by defining the elements of the array
Array_name[0]=value1
Array_name[1]=value2
...
The operations of the array are described below:
1. Elements that refer to an array:
How to reference an array element: ${array_name[index]}
Note: If index number is not given, the first element that references the array
Reference entire array all elements: ${array_name[*/@]}
Index of reference array: ${! Array_name[*/@]}
2. View the length of the array: the number of valid elements in the array:
${#ARRAY_NAME [*/@]}
3. Array slices:
${array_name:offset} Displays the index position that includes the offset number and all subsequent elements
4. Append elements:
1). Dense array:
array_name[${#ARRAY_NAME [*]}]=valuex
2). Sparse array
Array_name[index]=valuex index must be a number of unused array element indices;
5. Undo Array
Unset Array_Name
6. Deleting elements of an array
Unset Array_name[index]
About the array simple to remember here, the array is convenient for us to the large amount of data storage, reading and other operations, the use is greatly
Shell script Basics--arrays