Una característica de Bash es la posiblidad de utilizar una variable para conformar parte del nombre de otra variable, y luego acceder tanto al nombre como al valor de la variable mediante el uso del mecanismo de indirección, por ejemplo así:
Shell
1
2
3
4
5
6
7
8
9
10
#!/bin/bash
variable_uno="Yo soy 1"
variable_dos="Yo soy 2"
fororden inuno dos
do
variable="variable_$orden"
echo$variable=${!variable}
done
# Salida:
# variable_uno = Yo soy 1
# variable_dos = Yo soy 2
Una matriz o Arreglo es una variable que contiene múltiples valores pueda ser de un mismo tipo o de diferentes tipos. No hay un límite máximo al tamaño de una matriz, ni ningún requisito de que se indexan, los valores se asignan de forma contigua . El índice del campo comienza con cero.
ARRAY=()
Una declaración de matriz indexada y la inicializa para estar vacío. Esto también se puede utilizar para vaciar una matriz existente .
ARRAY[0]=
Generalmente establece el primer elemento de una matriz indexada . Si no existía un array matriz antes, se crea.
declare -a ARRAY
Una declaración de matriz indexada . No se inicializa un array existente .
declare -A ARRAY
Declara un array asociativo. Esta es la única manera de crear matrices asociativas.
A continuación, se repasaran 15 diferentes operaciones de matriz en bash :
1. Declaring an Array and Assigning values.-
In bash, array is created automatically when a variable is used in the format like,
name[index]=value
• name is any name for an array
• index could be any number or expression that must evaluate to a number greater than or equal to zero.You can declare an explicit array using declare -a arrayname.
Instead of initializing an each element of an array separately, you can declare and initialize an array by specifying the list of elements (separated by white space) with in a curly braces.
Syntax:
Shell
1
declare-aarrayname=(element1 element2 element3)
If the elements has the white space character, enclose it with in a quotes.
declare -a declares an array and all the elements in the parentheses are the elements of an array.
3. Print the Whole Bash Array.-
There are different ways to print the whole elements of the array. If the index number is @ or *, all members of an array are referenced. You can traverse through the array elements and print it, using looping statements in bash.
Shell
1
2
3
4
5
echo${Unix[@]}
# Add the above echo statement into the arraymanip.sh
#./t.sh
Debian Red hat Ubuntu Suse
Referring to the content of a member variable of an array without providing an index number is the same as referring to the content of the first element, the one referenced with index number zero.
4. Length of the Bash Array.-
We can get the length of an array using the special parameter called $#.
${#arrayname[@]} gives you the length of the array.
Shell
1
2
3
4
5
6
7
$catarraymanip.sh
declare-aUnix=('Debian''Red hat''Suse''Fedora');
echo${#Unix[@]}#Number of elements in the array
echo${#Unix}#Number of characters in the first element of the array.i.e Debian
$./arraymanip.sh
4
6
5. Length of the nth Element in an Array.-
${#arrayname[n]} should give the length of the nth element in an array.
Shell
1
2
3
4
5
6
7
8
9
10
11
12
$catarraymanip.sh
#! /bin/bash
Unix[0]='Debian'
Unix[1]='Red hat'
Unix[2]='Ubuntu'
Unix[3]='Suse'
echo${#Unix[3]}# length of the element located at index 3 i.e Suse
$./arraymanip.sh
4
6. Extraction by offset and length for an array.-
The following example shows the way to extract 2 elements starting from the position 3 from an array called Unix.
The above example returns the elements in the 3rd index and fourth index. Index always starts with zero.
7. Extraction with offset and length, for a particular element of an array.-
To extract only first four elements from an array element . For example, Ubuntu which is located at the second index of an array, you can use offset and length for a particular element of an array.
The above script will just print null which is the value available in the 3rd index. The following example shows one of the way to remove an element completely from an array.
In this example, ${Unix[@]:0:$pos} will give you 3 elements starting from 0th index i.e 0,1,2 and ${Unix[@]:4} will give the elements from 4th index to the last index. And merge both the above output. This is one of the workaround to remove an element from an array.
11. Remove Bash Array Elements using Patterns.-
In the search condition you can give the patterns, and stores the remaining element to an another array as shown below.
¿Te ha servido este sitio alguna vez? Cada script, cada línea de ayuda aquí es fruto de horas de trabajo y pasión por compartir. Si alguna vez resolviste un problema gracias a esta página, considera hacer una donación. Tu aporte —por pequeño que sea— mantiene vivo este proyecto y me impulsa a seguir creando.