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 47 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.

    1. Curso De Joyas /
      Usando Google Chrome Google Chrome 122.0.0.0 en Windows Windows NT

      Esta muy bien! Puedes seguir viendo cursos aqui https://donovanicaz91605.blognody.com/

      1. Wopi /
        Usando Google Chrome Google Chrome 122.0.0.0 en Windows Windows NT

        Ok! Me pasare ahora por tu pagina. Puedes visitar https://wopi.es/las-mejores-joyas/

    2. Seguidores De Tik Tok /
      Usando Google Chrome Google Chrome 122.0.0.0 en Windows Windows NT

      Esto es excelente. mira mi post sobre como ganar seguidores en tik tok http://www.opensource.platon.org/forum/projects/viewtopic.php?p=12573847#12573847

  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.

  19. aryastark /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    This guide has significantly improved my Bash scripting skills and I’m confident I can now use dynamic arrays effectively in my pokedoku projects.

  20. jsimitseo /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    The sheer size and selection of these web slots are mind-blowing. Great job. สล็อตเว็บใหญ่

  21. Zoey Nitzsche /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    It’s an amazing blog post, and it is really helpful as well.

  22. Georgina Harrison /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    Step into the world of Flores Santiago, where stunning floral arrangements mirror the unique blend of tradition and sophistication in Santiago. Our flowers are crafted to perfection, providing a touch of beauty and finesse to every celebration and sentiment. Explore Flores Santiago at its best, delivering floral masterpieces that echo the city’s charm in every bloom.

  23. jsimitseo /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    I’ve had bad experiences with slots breaking too easily. เว็บสล็อต

  24. jsimitseo /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    Your websites facilitate all the more each else volume is so engaging further serviceable It chooses me occur for withdraw reprise. I will in a split second snatch your rss channel to remain educated of any updates. รวมสล็อตทุกค่ายในเว็บเดียว

  25. jsimitseo /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    Here you will realize what is vital, it gives you a connection to an intriguing site page: เกมสล็อตโรม่า

  26. jsimitseo /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    I expounded on a comparable issue, I give you the connection to my site. เกมไพ่ป๊อกเด้ง

  27. BenIlaria /
    Usando Google Chrome Google Chrome 119.0.0.0 en Windows Windows NT

    First, you should define your goals. What’s the snaptik purpose of your pokedoku webinar? Do you want to educate, promote a product, or engage your audience?

  28. Bangalore escorts service /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    Thanks For Post

  29. 토토사이트 /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    I am so lucky to finally find this article. I am a person who deals with kind of this too.토토사이트 This article has huge information for me, and well prepared for people who need about this. I am sure this must be comepletly useful for many people in the world.

  30. Rank Xone /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    Online casinos are a great way to bond with friends. Whether we’re competing against each other or trying out new games together, it always makes for a good time. 플러스카지노

  31. UFAAUTO789 /
    Usando Google Chrome Google Chrome 120.0.0.0 en Windows Windows NT

    ufa789 เข้าสู่ระบบ เว็บแทงบอลที่ใหญ่ และการเงินมั่นคงที่สุด สล็อตออนไลน์ ไม่มีขั้นต่ำ ใช้ทุนน้อย เล่นได้ทุกเกม

  32. ufabet /
    Usando Google Chrome Google Chrome 107.0.0.0 en Windows Windows NT

    This is a smart blog. I mean it. You have so much knowledge about this issue, and so much passion. You also know how to make people rally behind it, obviously from the responses. Check this site: ufabet

  33. Corpus Christi Drywall Contractors /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    This is a great approach for enhancing script efficiency and configurability!

  34. jsimitseo /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    For what reason do just such a great amount of composed regarding this matter? Here you see more. best concierge doctor

  35. WilliamSEO /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    A debt of gratitude is in order for composing such a decent article, I staggered onto your blog and read a couple of post. I like your style of composing… รับจำนำรถ

  36. Bangalore escort /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    Thanks for This Post

  37. WilliamSEO /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    I think I have never observed such web journals ever that has finish things with all points of interest which I need. So sympathetically refresh this ever for us. รับจำนำรถ

  38. Bangalore escort /
    Usando Google Chrome Google Chrome 122.0.0.0 en Windows Windows NT

    Thanks For This Post

  39. WilliamSEO /
    Usando Google Chrome Google Chrome 122.0.0.0 en Windows Windows NT

    Well we extremely get a kick out of the chance to visit this site, numerous valuable data we can arrive. dispo travel spain

  40. Rank Xone /
    Usando Google Chrome Google Chrome 122.0.0.0 en Windows Windows NT

    I am checking for and I have to post a remark that «The substance of your post is excellent» Great work! จำนำรถ

  41. Bea /
    Usando Google Chrome Google Chrome 122.0.0.0 en Windows Windows NT

    This Bash scripting technique offers valuable flexibility to figure out what is purple drywall. Choose the approach that best fits your version and coding style.

  42. BETFLIXSUPERVIP /
    Usando Google Chrome Google Chrome 122.0.0.0 en Windows Windows NT

    site! I truly love how it is easy on my eyes and the data are well written. I am wondering how I could be notified when a new post has been made. I’ve subscribed to your RSS feed which must do the trick! Have a great day!betflik เว็บตรง

  43. MackenzieWynn /
    Usando Google Chrome Google Chrome 121.0.0.0 en Windows Windows NT

    I admire the depth prostadine of research evident in this blog post.

  44. liza memozi /
    Usando Google Chrome Google Chrome 122.0.0.0 en Windows Windows NT

    The article’s content is commendable in its depth and merits significant recognition. I sincerely wish that your efforts garner substantial attention. Please visit the page LOLbeans io to have moments of fun and entertainment.

Leave a Reply to Anónimo Cancle Reply