Publi

Píldora: Utilizar arrays con nombre dinámico en Bash

Arrays con nombre dinámico en Bash

Una de las grandes ventajas de los lenguajes interpretados es que podemos almacenar en una variable el nombre de otra variable y trabajar con su valor. ¿Punteros? Bueno, al final es parecido a la utilización de punteros en C, aunque aquí podemos hacer referencia por el mismo nombre de la variable incluso, previo filtrado y con mucho cuidado, preguntarle al usuario el de la variable para trabajar con ella.

Esto nos puede dar mucha flexibilidad en nuestro código. Por ejemplo, yo lo he utilizado para perfeccionar mi script de lectura de ficheros de configuración al que le podemos pasar también el nombre de la variable donde almacenar la configuración.

Arrays con nombre dinámico

En Bash, acceder a una variable cuyo nombre está contenido dentro de otra variable es sencillo, podemos hacerlo llamando a ${!NOMBREDEVARIABLE}. Podemos ver un ejemplo en el post referenciado.
El problema es que cuando son arrays no es tan inmediato. El objetivo es que, teniendo una variable que contiene el nombre del array podamos acceder a su información de una forma sencilla. Y El problema aquí viene en la versión de Bash que estemos utilizando. En este caso debemos hacerlo de una forma u otra dependiendo de si utilizamos una versión inferior a la 4.3 (más o menos salió en 2014) o si tenemos una versión posterior.

Ejemplo para Bash < 4.3

Lo siento, mira que no me gusta utilizar eval, pero claro, para estas versiones del intérprete necesitamos crear una cadena de caracteres con la llamada que vamos a hacer y luego evaluar dicha cadena de caracteres. Esto nos dará el valor que buscamos. Por ejemplo:

1
2
3
4
5
6
MIARRAY=("cero" "uno" "dos" "tres")
REFERENCIA="MIARRAY"

# Lo que necesitamos es acceder a cada uno de los elementos de MIARRAY a través de REFERENCIA.

eval echo \${$REFERENCIA[2]}

Si os fijáis, al construir la cadena. El primer símbolo de dólar ($) lo escapamos con la barra para que no se interprete. El que sí tiene que interpretar es el segundo, para que $REFERENCIA se transforme en el nombre del array.

Lo podemos hacer con arrays asociativos también sin problema, pero es algo complicado y realizamos demasiadas tareas para hacer referencia a una variable. Además no queda muy elegante o intuitivo tener que escapar un dólar y otro no.

Ejemplo para Bash >= 4.3

Para estas versiones, disponemos de un modificador en la orden declare (también llamada typeset) a través del cual podemos crear una variable de referencia que se comportará exactamente igual que nuestro array:

1
2
3
4
MIARRAY=("cero" "uno" "dos" "tres")
declare -n REFERENCIA="MIARRAY"

echo ${REFERENCIA[2]}

Además, de esta forma, el nombre de la variable puede venir dado en otra variable, con lo que podemos permitir que el usuario especifique el nombre de variable. Eso sí, con mucho cuidado.

Foto principal: unsplash-logoRuben Ortega

También podría interesarte....

There are 18 comments left Ir a comentario

  1. Today's Wordle /
    Usando Google Chrome Google Chrome 116.0.0.0 en Windows Windows NT

    Today’s Wordle is one of my favorite parts of the day, so it’s a paradox that happiest when we solve the puzzle quickly. My mornings are hectic. Today’s wordle is moderately challenging because of uncertainty. Today’s Wordle took the world by storm when it launched, and has kept players glued to their phone screens ever since.

  2. TEMPLE RUN 3 /
    Usando Google Chrome Google Chrome 116.0.0.0 en Windows Windows NT

    Thank you for your reasonable criticism. My neighbor and I are preparing to do some research on that temple run. We got a good book about it from our local library and most of the books are not as impactful as your information.

  3. bootsführerschein kaufen /
    Usando Google Chrome Google Chrome 116.0.0.0 en Mac OS X Mac OS X 10.15.7

    sportbootführerschein binnen und see, sportbootführerschein binnen prüfungsfragen, sportbootführerschein binnen kosten, sportbootführerschein binnen online, sportbootführerschein binnen wo darf ich fahren, sportbootführerschein binnen berlin, sportbootführerschein binnen segel, sportbootführerschein kaufen, sportbootführerschein kaufen erfahrungen, sportbootführerschein kaufen schwarz, sportbootführerschein see kaufen, sportbootführerschein binnen kaufen, sportbootführerschein see kaufen ohne prüfung, bootsführerschein kaufen, bootsführerschein kaufen polen, bootsführerschein kaufen erfahrungen, bootsführerschein online kaufen, bootsführerschein tschechien kaufen. https://sportbootfuhrerscheinkaufen.com/

    sportbootführerschein see

  4. 토토사이트 /
    Usando Google Chrome Google Chrome 116.0.0.0 en Windows Windows NT

    I am continually looking online for articles that can facilitate me. Thank you! 토토사이트

  5. https://therowdylender.com/ /
    Usando Google Chrome Google Chrome 116.0.0.0 en Windows Windows NT

    I stumbled on this while browsing on google I’ll be sure to come back. thanks for sharing. https://therowdylender.com/

  6. 메이저사이트 /
    Usando Google Chrome Google Chrome 116.0.0.0 en Windows Windows NT

    What’s up colleagues, its enormous post regarding educationand entirely defined, keep it up all the time. 메이저사이트

  7. 먹튀검증 /
    Usando Google Chrome Google Chrome 116.0.0.0 en Windows Windows NT

    F*ckin¦ Have you ever thought about including a little bit more than just your articles? 먹튀검증

  8. Lucas /
    Usando Google Chrome Google Chrome 116.0.0.0 en Windows Windows NT

    This technique offers valuable flexibility in Bash scripting, but you should choose the approach that best fits your version and coding style. | [url=https://www.mcallendrywall.com]https://www.mcallendrywall.com[/url]

  9. https://www.mcallendrywall.com /
    Usando Google Chrome Google Chrome 116.0.0.0 en Windows Windows NT

    This technique offers valuable flexibility in Bash scripting, but you should choose the approach that best fits your version and coding style.

  10. Monkey type /
    Usando Google Chrome Google Chrome 116.0.0.0 en Windows Windows NT

    Monkey Type is an engaging and interactive website that offers educational games, videos, and books for kids of all ages. It covers a wide range of subjects including math, reading, science, and problem-solving. With its entertaining content and educational focus, Funbrain provides a fun learning experience for children while reinforcing key academic skills.
    Monkey type

  11. 347 Area code /
    Usando Google Chrome Google Chrome 117.0.0.0 en Windows Windows NT

    https://www.area-codes.us/347-area-code/

    347 Area code is a New York City area code covering the Bronx, Queens, Brooklyn. This area code was assigned on February 19, 1999. It went live on October 1, 1999. 347 Area code is a general purpose code. Service area 347 overlaps with area codes 718 917 929. The dialing pattern for local calls within the same NPA (area code) is 1+10D.

  12. Nerdle Game Today /
    Usando Google Chrome Google Chrome 117.0.0.0 en Windows Windows NT

    Nerdle, the mathematical marvel of a game! A delight for the brainy bunch who like to flex their mental muscles while having a jolly good time. This charming game involves solving a plethora of mathematical puzzles to guide our little Nerdle through a maze of obstacles. Nerdle Game is the perfect amalgamation of fun and learning, and will leave you feeling satisfied and smarter than ever before. So why not give it a go and see if you can conquer the mathematical marvel that is Nerdle!

  13. 토토사이트추천 /
    Usando Google Chrome Google Chrome 117.0.0.0 en Windows Windows NT

    I love this information you have written here. It’s insightful and interesting. I will come back for more as soon as I can. Thank you. 토토사이트추천

  14. Megha Malik /
    Usando Google Chrome Google Chrome 109.0.0.0 en Windows Windows NT

    Thats Good For Who are Searching Something Else For Fun

  15. 토토사이트 /
    Usando Google Chrome Google Chrome 118.0.0.0 en Windows Windows NT

    What a great source of information. Such a wonderful collection of new ideas. I’ll definitely be back! 토토사이트

  16. 토토사이트 /
    Usando Google Chrome Google Chrome 119.0.0.0 en Windows Windows NT

    Thanks for this wonderful post! It has long been very helpful. I wish that you’ll carry on posting your wisdom with us. 토토사이트 I hope more and more people will find such a good article.

  17. Lubbock /
    Usando Google Chrome Google Chrome 119.0.0.0 en Windows Windows NT

    It’s a clever way to boost code adaptability and customization.

  18. Austin /
    Usando Mozilla Firefox Mozilla Firefox 120.0 en Windows Windows NT

    its me blippi Do you remember B L I P P I.

Leave a Reply