Array assignment
List assignment
Create an array with new elements
Array = ('First element ''' second element ''' third element ')
Subscript assignment
Explicitly specify the element index to create an array:
Array = ([3] = 'fourth element' [4] = 'th element ')
Assign values by index
Array [0] = 'first element'
Array [1] = 'second'
Assign values by name (associated array)
Declare-A array
Array [first] = 'first element'
Array [second] = 'second'
Dynamic assignment
Create an array with the output of other commands. For example, use seq to create an array from 1 to 10:
Array = ('seq 1 10 ')
Create an array from script parameters
Array = ("$ @")
In-loop assignment
While read-r; do
# Array + = ("$ REPLY") # Array append
Array [$ I] = "$ REPLY" # Assignment by index
Let I ++ # Increment index
Done <(seq 1 10) # command substitution
Echo $ {array [@]} # output: 1 2 3 4 5 6 7 8 9 10
Access array elements
Print the element with an index of 0
Echo "$ {array [0]}"
Print the last element (available from Bash 4.3)
Echo "$ {array [-1]}"
Print elements starting from index 1
Echo "$ {array [@]: 1 }"
Print the three elements starting from index 1
Echo "$ {array [@]: 1: 3 }"
Array change
Change by index
Initializes or updates a specific element in the array.
Array [10] = "elevenths element" # because it's starting with 0
Recovery
Modify the array and append the element to the end of the array.
Array + = ('fourth element' 'th element ')
Add element to the beginning of array
Array = ("new element" "$ {array [@]}")
Insert
Insert an element to the given index value
Arr = (a B c d)
# Insert an element at index 2
I = 2
Arr = ("$ {arr [@]: 0: $ I}" 'New' "$ {arr [@]: $ I }")
Echo "$ {arr [2]}" # output: new
Delete
Use uset to delete a specified index element
Arr = (a B c)
Echo "$ {arr [@]}" # outputs: a B c
Echo "$ {! Arr [@]} "# outputs: 0 1 2
Unset-v 'Arr [1]'
Echo "$ {arr [@]}" # outputs: a c
Echo "$ {! Arr [@]} "# outputs: 0 2
Re-index
When some elements are deleted from the array, you can use the following method to re-arrange the index, or you do not know whether the index has a time slot.
Array = ("$ {array [@]}")
Array length
$ {# Array [@]} returns the length of the $ {array [@]} array.
Array = ('First element ''' second element ''' third element ')
Echo "$ {# array [@]}" # gives out a length of 3
Iterative array elements
FileList = (file1.txt file2.txt file3.txt)
# Within the for loop, $ file is the current file
For file in "$ {fileList [@]}"
Do
Echo "$ file"
Done