Get the App
SLTechnology News&Howtos  ›  Network Security  › 

The usage of shell array

Shulou Source: shulou.com Published: 2022-06-01 04:19:44 09月30日 Update

Variable: the memory space that stores a single element:

Array (multiple contiguous memory spaces): contiguous memory space that stores multiple elements:

Array name:

Index: numbering starts at 0 and belongs to numeric index

Note: indexes can also support custom formats, not just numeric formats:

The array of bash supports sparse format

Reference elements in the array: ${ARRAY_ name [index]}

Declare an array:

Declare-an ARRAY_NAME

Declare-An ARRAY_NAME: associative array: kv

Assignment of array elements:

(1) assign only one element at a time:

ARRAY_ name [index] = VALUE

# weekdays [0] = "Sunday"

# weekdays [4] = "Thursday"

(2) assign all elements at once:

ARRAY_NAME= ("VAL1", "VAL2", "VAL3",...)

(3) only specific elements are assigned:

ARRAY_NAME= ([0] = "VAL1" [3] = "VAL2"...)

(4) read-an ARRAY

Reference an element in the array:

${ARRAY_ name [index]}

Note: omitting [INDEX] indicates referencing the element with subscript 0

Show all elements in the array:

${ARRAY_NAME [*]}, or ${ARRAY_NAME [@]}

Count the length of the array (the number of elements in the array):

${# ARRAY_NAME [*]}, ${# ARRAY_NAME [@]}

Reference elements in an array:

Fetch all the elements in the array in turn: ${ARRAY [@]} or ${ARRAY [*]}

Array slices:

Take out the element of specified length in the array: ${ARRAY [@]: offset:number}: also called array slice

Offset: the number of elements to skip

Number: the number of elements to be taken out

Example: # echo ${weekdays [@]: 1:2}

All elements after the offset is taken out: ${ARRAY [@]: offset}

# echo ${weekdays [@]: 1}

Append elements to the array:

ARRAY [${# ARRAY [*]}]

Delete an element from the array:

Unset ARRAY [INDEX]

Associative array:

Declare-An ARRAY_NAME

ARRAY_NAME= ([index_name] = 'val1' [index_name2='val2'...])

Tags: Array element number memory format space index multiple numeric length association storage support sparse subscript not only middle finger single variable offset Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Redmi Apple OPPO Reno Shulou Tech Info