Create and use array method summaries in Bash scripts

  • 2021-01-18 06:47:25
  • OfStack

Define an array in Bash

There are two ways to create a new array in an bash script. The first is to use the declare command to define an Array. This command defines an associative array named test_array.

[

$ declare -a test_array

]

You can also create arrays by assigning elements.

[

$ test_array=(apple orange lemon)

]

Accessing Array Elements

Like other programming languages, bash array elements can start with an index number starting at 0, then 1, 2, 3... n access begins. This also applies to associative arrays with index numbers.

[

$ echo ${test_array[0]}

apple

]

Prints all elements of an array using @ or * instead of a specific index number.

[

$ echo $ {test_array [@]}

apple orange lemon

]

Loop through an array

You can also loop through array elements using the bash script. Loops are useful for iterating through all the elements of an array one by one and performing some operations on them.

[

for i in ${test_array[@]}

do

echo $i

don

]

Adds a new element to the array

You can add any number of elements to an existing array using the (+=) operation. Just add new elements, such as:

[

$ test_array+=(mango banana)

]

To view array elements after adding ES79en:

[

$ echo ${test_array[@]}

apple orange lemon mango banana

]

Update array elements

To update an array element, simply assign any new values to the existing array via the index. Let's use grapes to change the current array element at index 2.

[

$ test_array[2]=grapes

]

To view array elements after adding new elements:

[

$ echo ${test_array[@]}

apple orange grapes mango banana

]

Delete array elements

You can simply remove any array element using the index number. The following is to remove the element at index 2 from the array in the bash script.

[

$ unset test_array [2]

]

To view array elements after adding new elements:

[

$ echo ${test_array[@]}

apple orange mango banana

]

Related articles: