English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Shell Arrays

Un array può contenere più valori. Bash Shell supporta solo array unidimensionali (non array multidimensionali), non è necessario definire la dimensione dell'array all'inizializzazione (simile a PHP).

Come nella maggior parte dei linguaggi di programmazione, l'indice degli elementi dell'array parte da 0.

Le array di Shell sono rappresentate da parentesi quadre, gli elementi sono separati dal simbolo "spazio", il formato grammaticale è il seguente:

array_name=(value1 value2 ... valuen)

Esempio online

#!/bin/bash
# author:Base Tutorial Website
# url:it.oldtoolbag.com
my_array=(A B "C" D)

Possiamo anche utilizzare l'indice per definire l'array:

array_name[0]=value0
array_name[1]=value1
array_name[2]=value2

Leggere l'array

Il formato generale per leggere il valore di un elemento dell'array è:

${array_name[index]}

Esempio online

#!/bin/bash
# author:Base Tutorial Website
# url:it.oldtoolbag.com
my_array=(A B "C" D)
echo "The first element is: ${my_array[0]}"
echo "The second element is: ${my_array[1]}"
echo "The third element is: ${my_array[2]}"
echo "The fourth element is: ${my_array[3]}"

Execute the script, the output is as follows:

$ chmod +x test.sh 
$ ./test.sh
The first element is: A
The second element is: B
The third element is: C
The fourth element is: D

Get all elements of an array

Using @ or * to get all elements of an array, for example:

#!/bin/bash
# author:Base Tutorial Website
# url:it.oldtoolbag.com
my_array[0]=A
my_array[1]=B
my_array[2]=C
my_array[3]=D
echo "The elements of the array are: ${my_array[*]}"
echo "The elements of the array are: ${my_array[@]}"

Execute the script, the output is as follows:

$ chmod +x test.sh 
$ ./test.sh
The elements of the array are: A B C D
The elements of the array are: A B C D

Get the length of an array

The method to get the length of an array is the same as that of getting the length of a string, for example:

#!/bin/bash
# author:Base Tutorial Website
# url:it.oldtoolbag.com
my_array[0]=A
my_array[1]=B
my_array[2]=C
my_array[3]=D
echo "Number of array elements: ${#my_array[*]}"
echo "Number of array elements: ${#my_array[@]}"

Execute the script, the output is as follows:

$ chmod +x test.sh 
$ ./test.sh
Number of array elements: 4
Number of array elements: 4