Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables as part of variable name in unix [duplicate]

Tags:

shell

unix

I want to name variable as a_${v}.

for example : v can be 2013 2014

I am now declaring a variable to a_${v}

a_${v}=hI # a_2013 should be Hi

v=2014

so a_${v}=Hello # a_2014 should be Hello

I tried using eval command though it is not throwing error while assigning a value but I am not able to extract the value of variable name

$ v=2013

$ eval a_${v}=Hi


$ v=2014

$ eval a_${v}=Hello

echo ${a_${v}}

is not working.. :(

I am using bash and I don't want to change the variable name i.e dn't want to assign the value to another value

like image 777
Vishal Srivastava Avatar asked Sep 07 '14 09:09

Vishal Srivastava


People also ask

How do you name variables with other variables?

However, if you simply want to store some data in a key-value fashion, you can use a dictionary: var data = new Dictionary<string, decimal>(); The first type argument is the key, and the second is the value. Do note that the values all have to be of the same type, or a type that derives from some common type.

How do I create a dynamic variable in bash?

You can simply store the name of the variable in an indirection variable, not unlike a C pointer. Bash then has a syntax for reading the aliased variable: ${! name} expands to the value of the variable whose name is the value of the variable name . You can think of it as a two-stage expansion: ${!


2 Answers

In bash you can do the below (note the exclamation mark syntax in the last line):

#!/bin/bash

a_2014='hello 2014'
year=2014
varname=a_${year}
echo ${!varname}
like image 69
bobah Avatar answered Nov 20 '22 02:11

bobah


Parameter expansion is not recursive, therefore the text ${a_${v}} is really The contents of the variable whose name is 'a_${v}', and the shell complains that this variable name is not valid.

You can achieve recursive expansion with the eval command, as in

eval printf '%s\n' "\${a_${v}}"

To increase the readability and maintainability of your shell scripts, you should limit the use of such constructs and wrap them in appropriate structures. See rc.subr provided on FreeBSD systems for an example.

like image 27
Michaël Le Barbier Avatar answered Nov 20 '22 02:11

Michaël Le Barbier