0

Hello and thank you for your assistance in advance. I am trying to update a variable that has a variable name within it.

I am trying to keep it simple as follow:

loc=abc 
value='Jul 02 2018 12:01' 
echo ${loc}datetime #results in abcdatetime 
eval ${loc}datetime="\"$value\"" 
echo $abcdatetime results in Jul 02 2018 12:01  

is there a way to do something similar like ${loc}datetime=$(value); or $(({loc}datetime=$value)) I want to get away from using "eval" and the "\$value\"" Thank you again SteveO.

  • For an extended discussion, see [BashFAQ #6](https://mywiki.wooledge.org/BashFAQ/006#Assigning_indirect.2Freference_variables). – Charles Duffy Jul 02 '18 at 19:38
  • ...that said, an associative array probably makes more sense for your use case. `declare -A datetime; datetime["abc"]='Jul 02 2018 12:01'`; no need for multiple variables at all, just make the one variable you have be a map from strings to strings. – Charles Duffy Jul 02 '18 at 19:39
  • Thank you however the time/date is not being generated it is part of a value being read in from a file and assigned to value. Then I need to take that $value and assign it to another variable ${loc}xyz.... – user1683269 Jul 02 '18 at 19:49
  • and yes the documentation shows the method I am currently useing eval "${ref}=\$value" – user1683269 Jul 02 '18 at 19:51
  • which is eval ${loc}abc="\"$value\"" – user1683269 Jul 02 '18 at 19:51
  • What does the generated vs read-from-a-file distinction matter at all? Why do you think this means you can't use the answers from the preexisting question? – Charles Duffy Jul 02 '18 at 19:59
  • ...and if you read the FAQ entry more carefully, it shows plenty of non-`eval`-based approaches; indeed, [BashFAQ #48](http://mywiki.wooledge.org/BashFAQ/048) goes into detail on why `eval` shouldn't be used. – Charles Duffy Jul 02 '18 at 20:00
  • To clarify my suggestion about using associative arrays above -- a program that's designed well won't depend on variables named `${loc}xyz` at all, and should use `loc[$xyz]` instead. Even `xyz${loc}` is a better convention, because you can iterate over all variables whose names start with a prefix efficiently, but can't do the same with a suffix. So *if you can*, you should change the larger program to no longer ask you to set variables named with the form `${loc}xyz`. If you can't, though, the linked question and FAQ both go into details on how to do what you're asking for. – Charles Duffy Jul 02 '18 at 20:01
  • Take `printf -v "${loc}datetime" '%s' "$value"`, for example -- in no way does it care whether `loc` comes from a file. – Charles Duffy Jul 02 '18 at 20:06

0 Answers0