Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

135
Vistas
Using "read" to set variables

In bash from the CLI I can do:

$ ERR_TYPE=$"OVERLOAD"
$ echo $ERR_TYPE
OVERLOAD
$ read ${ERR_TYPE}_ERROR
1234
$ echo $OVERLOAD_ERROR
1234

This works great to set my variable name dynamically; in a script it doesn't work. I tried:

#!/bin/env bash

ERR_TYPE=("${ERR_TYPE[@]}" "OVERLOAD" "PANIC" "FATAL")

for i in "${ERR_TYPE[@]}"
do
   sh -c $(echo ${i}_ERROR=$"1234")
done
echo $OVERLOAD_ERROR # output is blank

   # I also tried these:
   # ${i}_ERROR=$(echo ${i}_ERROR=$"1234") # command not found
   # read ${i}_ERROR=$(echo ${i}_ERROR=$"1234") # it never terminates

How would I set a variable as I do from CLI, but in a script? thanks

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

When you use dynamic variables names instead of associative arrays, you really need to question your approach.

err_type=("OVERLOAD" "PANIC" "FATAL")
declare -A error
for type in "${err_type[@]}"; do
    error[$type]=1234
done

Nevertheless, in bash you'd use declare:

declare "${i}_error=1234"

Your approach fails because you spawn a new shell, passing the command OVERLOAD_ERROR=1234, and then the shell exits. Your current shell is not affected at all.

Get out of the habit of using ALLCAPSVARNAMES. One day you'll write PATH=... and then wonder why your script is broken.

over 4 years ago · Santiago Trujillo Denunciar

0

I'd use eval. I think this would be considered bad practice though (it had some thing to do with the fact that eval is "evil" because it allows bad input or something):

eval "${i}_ERROR=1234"
over 4 years ago · Santiago Trujillo Denunciar

0

If the variable will hold a number, you can use let.

#!/bin/bash

ERR_TYPE=("OVERLOAD" "PANIC" "FATAL")

j=0
for i in "${ERR_TYPE[@]}"
do
  let ${i}_ERROR=1000+j++
done
echo $OVERLOAD_ERROR
echo $PANIC_ERROR
echo $FATAL_ERROR

This outputs:

1000
1001
1002
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda