Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Create and use array method summaries in Bash scripts

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report