Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get content from variable whose name is taken from another variable

I am doing some shell scripting.

I use this construction for creating new variables:

eval ${ARG}_ext=fastq

which works pretty nice because then I can use those newly created variable directly like this:

$file_ext

Now I want to assign value to the variable called extension:

extension=

The assigned value should be one found in variable ${ARG}_ext. Please, how can i do that?

I have tried

extension=eval ${ARG}_ext;

but this gives me name of the variable and I want its value. Thanks.

like image 525
Perlnika Avatar asked Jun 17 '26 02:06

Perlnika


2 Answers

Try:

$ extension=$(eval "echo \$${ARG}_ext")
like image 68
Fredrik Pihl Avatar answered Jun 19 '26 18:06

Fredrik Pihl


Not a direct answer, but have you considered using associative arrays instead:

declare -A myhash
ARG=file
myhash[${ARG}_ext]='fastq'
extension="${myhash[${ARG}_ext]}"
echo "$extension"

Note that declare creates a local variable if used inside a function, so declare the associated array in global scope if you need it globally. (The newest versions of bash add a -g (global) option to declare that solves this issue.)

like image 39
William Avatar answered Jun 19 '26 18:06

William



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!