0

I have the following setup:

NODEX="sn1"                   

varname="${NODEX}_payTimestamp"

echo "${!varname}"

> sn1_payTimestamp

How can I set a value to the variable “sn1_payTimestamp”?

Something like that?

${!varname}=$(date --utc +%Y%m%d_%H%M%SZ);

Thx in advance

Update

associative arrays seem to be the best solution. Is there a good way to store them into and read them from a text file? This is why I intended to use that “variable variable names”.

5
  • 1
    Don't. Use an associative array instead. Almost all cases where variable indirection seems like it might be a good idea are handled better, easier, and safer with an associative array.
    – cas
    Jul 13, 2022 at 4:45
  • Thx @cas. Is there a good way to store associative arrays into and read them from a text file?
    – bjoern
    Jul 13, 2022 at 4:57
  • 1
    Depends on the data, but in general, you can use printf or echo or whatever plus redirection to write them, and you can use mapfile to read them. or use a while-read loop. If your requirements are complex or if performance is important then bash is the wrong language for the job, look into using awk or perl or python or something. Shell is not a good language for processing data. It is great at coordinating other programs to process data, but terrible at doing the processing itself. It's the wrong tool for that job.
    – cas
    Jul 13, 2022 at 5:04
  • 1
    BTW, deciding that you need to use variable indirection to achieve your goals is a pretty good sign that what you are trying to do is too complex for a shell script, and that it's time to Learn Perl
    – cas
    Jul 13, 2022 at 5:06
  • Thank you, will have a look on your proposals. And yes indeed, the script got really complex and it might make sense to rewrite it in Perl or Python.
    – bjoern
    Jul 13, 2022 at 6:13

2 Answers 2

2

If you're on Bash, switch to using an associative array instead:

#!/bin/bash
declare -A paytimestamps
node=sn1
paytimestamps[$node]=$(date --utc +%Y%m%d_%H%M%SZ);
echo "${paytimestamps[$node]}"

Or if you really want to use named variables, use a nameref:

#!/bin/bash
node=sn1
declare -n "ref=paytimestamps_$node"
ref=$(date --utc +%Y%m%d_%H%M%SZ);
echo "$ref"

See Does bash provide support for using pointers?

1
  • Thank you! Is there a good way to store associate arrays into and read them from a text file?
    – bjoern
    Jul 13, 2022 at 4:58
0

Use eval. It will parse its arguments as a normal statement:

#!/bin/bash
NODEX="sn1"                   
varname="${NODEX}_payTimestamp"

eval $varname=$(date --utc +%Y%m%d_%H%M%SZ)

echo $varname
echo ${!varname}
2
  • And also causes piles of issues, up to arbitrary command execution, if the data can contain any shell special character. Like & or ;.
    – ilkkachu
    Jul 12, 2022 at 22:37
  • Thx. I’ve learned eval is evil. 😇
    – bjoern
    Jul 13, 2022 at 4:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .