Publi

[Bash] Llamar a una variable cuyo nombre lo contiene otra variable

numbers

Imaginemos el caso en que tenemos tres variables (ROJO=5 ; VERDE=6 ; AZUL=7), y una función a la que le pasaremos el nombre del color y nos devolverá su valor (así visto parece tontería, pero luego podremos normalizarlo, aclararlo, oscurecerlo, etc).

1
2
3
4
5
6
7
8
9
10
ROJO=5
VERDE=6
AZUL=7

function get_color()
{
   echo ${!1}
}

get_color ROJO

Efectivamente si en Bash escribimos ${!VARIABLE} no nos devuelve el nombre que contiene la variable, sino que devuelve el valor de la variable cuyo nombre es $VARIABLE.

Otro ejemplo, quizás un poco más claro:

1
2
3
4
5
6
7
MALAGA=568507
SEVILLA=703021
HUELVA=149410

MICIUDAD=MALAGA

echo ${!MICIUDAD}

Tenemos tres ciudades, Málaga, Sevilla y Huelva, cada una con su variable y su valor (la población extraída de la Wikipedia), por otro lado tenemos la variable MICIUDAD cuyo valor será una de las tres ciudades. Ahora, queremos saber la población de MICIUDAD, pues debemos acceder a la variable $MALAGA para ello con el operador ${!VARIABLE} lo hacemos de forma sencilla.

También podría interesarte....

There are 3 comments left Ir a comentario

  1. Pingback: Bitacoras.com /

  2. lily lily /
    Usando Google Chrome Google Chrome 109.0.0.0 en Windows Windows NT

    Values can be identified as constants in bitlife programs by using the const qualitative keyword. A declared variable becomes a constant when this keyword is used. Most compilers will signal any intentional or accidental alteration of its value. Because the variable’s values cannot be altered once the const qualitative keyword has been used, the programmer must set the initial value at the time of declaration.

  3. terraria /
    Usando Google Chrome Google Chrome 113.0.0.0 en Windows Windows NT

    You can dig, fight, explore, and build as you try to stay alive, make money, and become famous. Will you go deep into vast spaces to look for wealth and raw materials that you can use to make gear, machines, and looks that are always getting better? Maybe you’d rather fight bigger and stronger enemies to see how strong you are. You might decide to build your own city to house the many strange friends you might meet on your journeys.
    terraria

Leave a Reply