Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda