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”.

bjoern
  • 55
  • 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 '22 at 04:45
  • Thx @cas. Is there a good way to store associative arrays into and read them from a text file? – bjoern Jul 13 '22 at 04: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 '22 at 05: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 '22 at 05: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 '22 at 06:13

2 Answers2

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?

ilkkachu
  • 138,973
  • Thank you! Is there a good way to store associate arrays into and read them from a text file? – bjoern Jul 13 '22 at 04: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}

White Owl
  • 5,129