Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!