Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to parse the Shell array

Shulou Source: shulou.com Published: 2022-06-01 03:07:43 10月19日 Update

This article introduces you how to parse the Shell array, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Bash supports one-dimensional arrays (not multidimensional arrays) and does not limit the size of the array.

Similar to the C language, the subscripts of array elements are numbered starting with 0. The subscript is used to get the elements in the array, which can be an integer or an arithmetic expression whose value should be greater than or equal to 0.

Define array

In Shell, arrays are represented by parentheses, and array elements are separated by a "space" symbol. The general form of defining an array is:

Array name = (value 1, value 2. Value n)

For example:

Array_name= (value0 value1 value2 value3)

Or

Array_name= (value0value1value2value3)

You can also define individual components of an array:

Array_name [0] = value0array_name [1] = value1array_ name [n] = valuen

There can be no use of consecutive subscripts, and there is no limit to the range of subscripts.

Read array

The general format for reading array element values is:

${Array name [subscript]}

For example:

Valuen=$ {array_ name[n]}

Use the @ symbol to get all the elements in the array, such as:

Echo ${array_name [@]}

Get the length of the array

Get the length of an array in the same way as you get the length of a string, for example:

# get the number of array elements length=$ {# array_name [*]} # or length=$ {# array_name [*]} # get the length of a single element of the array lengthn=$ {# array_ name [n]} on how to parse the array, that's all. I hope the above can be helpful to you and learn more. If you think the article is good, you can share it for more people to see.

Tags: Array element subscript length content method more symbol help support yes same number interest component single size character string boy Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Docker Shulou Tech Info NVidia MySQL