Get the App
SLTechnology News&Howtos  ›  Servers  › 

Create and use array method summaries in Bash scripts

Shulou Source: shulou.com Published: 2022-06-02 03:41:05 09月12日 Update

Define an array in Bash

There are two ways to create a new array in a 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 an array by assigning elements.

$test_array= (apple orange lemon)

Access array elements

Like other programming languages, bash array elements can start at 0 with index numbers, and then from 1, 2, 3... N start the access. This also applies to associative arrays with numeric index numbers.

$echo ${test_array [0]}

Apple

Use @ or * instead of a specific index number to print all elements of the array.

$echo ${test_array [@]}

Apple orange lemon

Loop through an array

You can also use iterations in bash scripts to access array elements. Loops are useful for iterating through all array elements one by one and performing some operations on them.

For i in ${test_array [@]}

Do

Echo $I

Don

Add a new element to the array

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

$test_array+= (mango banana)

View the array elements after adding new:

$echo ${test_array [@]}

Apple orange lemon mango banana

Update array elements

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

$test_array [2] = grapes

View the array elements after adding new elements:

$echo ${test_array [@]}

Apple orange grapes mango banana

Delete array elements

You can simply delete any array element using an index number. Here is the element at index 2 removed from the array in the bash script.

$unset test_array [2]

View the array elements after adding new elements:

$echo ${test_array [@]}

Apple orange mango banana

Tags: Array element index index number script loop command association allocation update method creation just can pass number quantity useful programming language programming Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info OPPO Reno Huawei macOS NVidia