linux:bash:arrays

Diferències

Ací es mostren les diferències entre la revisió seleccionada i la versió actual de la pàgina.

Enllaç a la visualització de la comparació

Ambdós costats versió prèvia Revisió prèvia
Següent revisió
Revisió prèvia
linux:bash:arrays [24/08/2018 00:30] – [+ asignaciones] matelinux:bash:arrays [09/10/2018 04:48] (actual) – [declaración e inicialización] mate
Línia 1: Línia 1:
-~~NOTOC~~ 
- 
 = arrays bash = arrays bash
 +~~NOTOC~~
 {{tag>linux bash pendiente wiki}} {{tag>linux bash pendiente wiki}}
 /via: [[http://www.thegeekstuff.com/2010/06/bash-array-tutorial/]] /via: [[http://www.thegeekstuff.com/2010/06/bash-array-tutorial/]]
  
-<callout type="info" title="pendiente" icon="true">http://wiki.bash-hackers.org/syntax/arrays?rev=1534920675</callout>+<callout type="info" title="más información de interés (arrays indirection)" icon="true">http://wiki.bash- 
 +hackers.org/syntax/arrays?rev=1534920675</callout> 
 +<callout type="info" title="más información de interés (arrays asociativos)" icon="true">https://www.artificialworlds.net/blog/2012/10/17/bash-associative-array-examples/</callout> 
 + 
 +== declaración e inicialización 
 +<code bash; indices numéricos> 
 +declare -a array=(valor0 'valor uno' 'valor dos'
 +</code> 
 +<code bash; asociativo> 
 +declare -A array=( [indice1]=valor0 [indice2]='valor uno' [indice3]='valor dos'
 +# es necesario una versión 4+ de BASH para disponer de Arrays asociativos 
 +</code> 
 + 
 == declaración y asignación == declaración y asignación
 <code bash> <code bash>
Línia 14: Línia 26:
 array[1]='valor uno' array[1]='valor uno'
 array[2]='valor dos' array[2]='valor dos'
-</code> 
- 
-== inicialización durante declaración 
-<code bash> 
-declare -a array=(valor0 'valor uno' 'valor dos') 
 </code> </code>
  
Línia 34: Línia 41:
  
 == recuperación == recuperación
 +^Sintaxis ^ Descripción ^
 +| **${ARRAY[N]}** | recupera el elemento N  |
 +| **${ARRAY[S]}** | recupera el elemento S en arrays **asociativos** |
 +| **"${ARRAY[@]}"** | \\ Recupera todos los elementos\\ Si está entrecomillado, @ devuelve cada elemento, %%*%% devuelve un único resultado con todos los elementos.\\ Si no lo está, las dos devuelven lo mismo |
 +| **${ARRAY[@]}** | ::: |
 +| ** "${ARRAY[*]}"** | ::: |
 +| **${ARRAY[*]}** | ::: |
 +| **"${ARRAY[@]:N:M}"** | \\ De funcionamiento similar a la regla anterior, añade que devuelve desde el elemento N, M elementos |
 +| **${ARRAY[@]:N:M}** | ::: |
 +| **"${ARRAY[*]:N:M}"** | ::: |
 +| **${ARRAY[*]:N:M}** | ::: |
 +
 +=== mostar array/elementos/subcadenas
 +  * todo el array: ''echo ${array[@]}''
 +  * un elemento: ''echo ${array[n]}''
 +  * del elemento n al m: ''echo ${array[@]:n:m}''
 +  * del elemento n, subcadena a-b: ''echo ${array[n]:a:b}''
 +  * todos los items del array: ''${array[*]}''
 +  * todos los índices del array:  ''${!array[*]}''
 +  * número de items:  ''${#array[*]}''
 +  * vía: [[http://www.linuxjournal.com/content/bash-arrays]]
 +
 +<button collapse="original-recuperacion" size="xs">original</button>
 +
 +<collapse id="original-recuperacion" collapsed="true">
 +
 ^Syntax ^Description ^ ^Syntax ^Description ^
-''${ARRAY[N]}'' | Expands to the value of the index ''N'' in the **indexed** array ''ARRAY''. If ''N'' is a negative number, it's treated as the offset from the maximum assigned index (can't be used for assignment) - 1  | +**${ARRAY[N]}** | Expands to the value of the index ''N'' in the **indexed** array ''ARRAY''. If ''N'' is a negative number, it's treated as the offset from the maximum assigned index (can't be used for assignment) - 1  | 
-''${ARRAY[S]}'' | Expands to the value of the index ''S'' in the **associative** array ''ARRAY''. | +**${ARRAY[S]}** | Expands to the value of the index ''S'' in the **associative** array ''ARRAY''. | 
-''"${ARRAY[@]}"\\ ${ARRAY[@]}\\ "${ARRAY[*]}"\\ ${ARRAY[*]}'' | Similar to [[scripting:posparams#mass_usage| mass-expanding positional parameters]], this expands to all elements. If unquoted, both subscripts ''*'' and ''@'' expand to the same result, if quoted, ''@'' expands to all elements individually quoted, ''*'' expands to all elements quoted as a whole. | +**"${ARRAY[@]}"\\ ${ARRAY[@]}\\ "${ARRAY[*]}"\\ ${ARRAY[*]}** | Similar to [[scripting:posparams#mass_usage| mass-expanding positional parameters]], this expands to all elements. If unquoted, both subscripts ''*'' and ''@'' expand to the same result, if quoted, ''@'' expands to all elements individually quoted, ''*'' expands to all elements quoted as a whole. | 
-''"${ARRAY[@]:N:M}"\\ ${ARRAY[@]:N:M}\\ "${ARRAY[*]:N:M}"\\ ${ARRAY[*]:N:M}'' | Similar to what this syntax does for the characters of a single string when doing [[syntax:pe#substring_expansion| substring expansion]], this expands to ''M'' elements starting with element ''N''. This way you can mass-expand individual indexes. The rules for quoting and the subscripts ''*'' and ''@'' are the same as above for the other mass-expansions. |+**"${ARRAY[@]:N:M}"\\ ${ARRAY[@]:N:M}\\ "${ARRAY[*]:N:M}"\\ ${ARRAY[*]:N:M}** | Similar to what this syntax does for the characters of a single string when doing [[syntax:pe#substring_expansion| substring expansion]], this expands to ''M'' elements starting with element ''N''. This way you can mass-expand individual indexes. The rules for quoting and the subscripts ''*'' and ''@'' are the same as above for the other mass-expansions. | 
 + 
 +</collapse> 
 +== metadata 
 +^ Syntaxis ^Descripción ^ 
 +|**${#ARRAY[N]}** | Longitud del elemento N | 
 +|**${#ARRAY[STRING]}** | idem en **asociativo** | 
 +|**${#ARRAY[@]}**\\ **${#ARRAY[*]}**| Número de elementos | 
 +|**${!ARRAY[@]}**\\ **${!ARRAY[*]}**| Extrae los índices del array, @ elemento a elemento, %%*%% en un bloque (desde BASH 3.0)| 
 + 
 +=== longitud 
 +  * del array: ''echo ${#array[@]}'' 
 +  * del primer elemento: ''echo ${#array}'' 
 +  * del tercero: ''echo ${#array[2]}'' 
 + 
 +<button collapse="original-metadata" size="xs">original</button> 
 + 
 +<collapse id="original-metadata" collapsed="true">
  
-== metada 
 ^Syntax ^Description ^ ^Syntax ^Description ^
-|''${#ARRAY[N]}'' |Expands to the **length** of an individual array member at index ''N'' (**stringlength**) | +|**${#ARRAY[N]}** |Expands to the **length** of an individual array member at index **N** (**stringlength**) | 
-|''${#ARRAY[STRING]}'' | Expands to the **length** of an individual associative array member at index ''STRING'' (**stringlength**) | +|**${#ARRAY[STRING]}** | Expands to the **length** of an individual associative array member at index **STRING** (**stringlength**) | 
-|''${#ARRAY[@]}''\\ ''${#ARRAY[*]}''|Expands to the **number of elements** in ''ARRAY'' +|**${#ARRAY[@]}**\\ **${#ARRAY[*]}**|Expands to the **number of elements** in **ARRAY** 
-|''${!ARRAY[@]}''\\ ''${!ARRAY[*]}''|Expands to the **indexes** in ''ARRAY'' since BASH 3.0|+|**${!ARRAY[@]}**\\ **${!ARRAY[*]}**|Expands to the **indexes** in **ARRAY** since BASH 3.0| 
 + 
 +</collapse>
  
 == destrucción == destrucción
Línia 56: Línia 107:
  
 usar siempre comillas para encerrar la variable para evitar problemas con las variables glob usar siempre comillas para encerrar la variable para evitar problemas con las variables glob
-== mostar array/elementos/subcadenas 
-  * todo el array: ''echo ${array[@]}'' 
-  * un elemento: ''echo ${array[n]}'' 
-  * del elemento n al m: ''echo ${array[@]:n:m}'' 
-  * del elemento n, subcadena a-b: ''echo ${array[n]:a:b}'' 
- 
-== longitud 
-  * del array: ''echo ${#array[@]}'' 
-  * del primer elemento: ''echo ${#array}'' 
-  * del tercero: ''echo ${#array[2]}'' 
  
 == adición / eliminación / sustitución elementos == adición / eliminación / sustitución elementos
Línia 78: Línia 119:
 == cargar contenido de un fichero == cargar contenido de un fichero
   * ''array=(` cat file `)''   * ''array=(` cat file `)''
- 
-== funky constructs 
-  * todos los items del array: ''${array[*]}'' 
-  * todos los índices del array:  ''${!array[*]}'' 
-  * número de items:  ''${#array[*]}'' 
-  * vía: [[http://www.linuxjournal.com/content/bash-arrays]] 
  
 == ejemplos == ejemplos
Línia 116: Línia 151:
  
 arr=("${array[@]}") arr=("${array[@]}")
-echo "After @ quoted expansion: ${#arr[*]}"+echo "After @ quoted expansion: ${#arr[@]}"
 for ix in ${!arr[*]} for ix in ${!arr[*]}
 do do
  • linux/bash/arrays.1535095847.txt.gz
  • Darrera modificació: 24/08/2018 00:30
  • per mate