Dynamic variable name in bash


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Dynamic variable name in bash
# 1  
Old 02-12-2017
Dynamic variable name in bash

Hello,

I'm trying to build a small script to store a command into a dynamic variable, and I have trouble assigning the variable.

Code:
#!/bin/bash

declare -a var1array=("value1" "value2" "value3")
var1arraylength=${#var1array[@]}

for (( i=1; i<${var1arraylength}+1; i++ ));
do
     mkdir "${var1array[$i-1]}"

     var2=${var1array[$i-1]}
     
     "$var2Value01=$(command 01)"
     "$var2Value02=$(command 02)"

     if [ ! -z $var2Value01] ; then
          echo $var2Value01 > file-$var2Value01.err
     else
          echo "No errors in $var2Value01"
     fi

     if [ ! -z $var2Value01] ; then
          echo $var2Value01 > file-$var2Value02.err
     else
          echo "No errors in $var2Value01"
     fi


done

I imagine the problem with this script is when assigning the dynamic variables
Code:
"$var2Value01=$(command 01)"

and
Code:
"$var2Value02=$(command 02)"

Does anyone had similar issues, and if yes how can this be solved?
I've tried with
Code:
 eval "$var2Value01=$(command 01)"

but without any luck.
# 2  
Old 02-12-2017
Quote:
Originally Posted by alex2005
I imagine the problem with this script is when assigning the dynamic variables
Code:
"$var2Value01=$(command 01)"

and
Code:
"$var2Value02=$(command 02)"

This is correct, but maybe in a different way than you may have thought.

The shell parses the commandline in several distinct steps and one of these steps is the "expansion" of variables - that is, replacing them with their values. The problem is that all variables are expanded at the same time.

Therefore you need eval, because your construct implies a "second pass of expansion" to be applied onto your line. Unfortunately you cannot selectively restart a certain parsing step. You can only restart the whole process from the beginning. Therefore you perhaps need - to make your line work - to distinguish between the parts that are meant to be expanded in the first pass and the ones meant to be expanded in the second one. Notice that the shell "consumes" some characters and if you need to have them still there you need to escape them properly so that they are not consumed in the first pass:

Code:
$ echo "two words"
two words
$ echo \"two words\"
"two words"

$ eval echo "two words"
two words
$ eval echo \"two words\"
two words
$ eval echo \\"two words\\"
two words
$ eval echo \\\"two words\\\"
"two words"

To really understand all the differences between these lines pipe the echo-output into wc -w to count the words for every command variation.

A word about eval in general: stay away from it if you can! Most times you can find a solution where you do it differently and you don't need eval at all. This is (in almost every case) preferable, because eval is very dangerous. It is very easy to lose track of what really gets executed and why. Only if there is definitely no other way then use it as a last resort.

I hope this helps.

bakunin
These 2 Users Gave Thanks to bakunin For This Post:
# 3  
Old 02-12-2017
In addition to what bakunin has already said, please consider the following...

I am having difficulty understanding what you are trying to do. The shell command language defined by the POSIX standards does not provide for dynamic variables in the shell command language. And bash, ksh, and most other shells I normally use do not support dynamic variables even as an extension to the standards. And, I don't see anything in your code that shows any need for dynamic variables.

What are you attempting to do with the following commands:
Code:
     "$var2Value01=$(command 01)"
     "$var2Value02=$(command 02)"

? The variables var2Value01 and var2Value02 have not been defined in this script, so the strings on the left side of the = will expand to empty strings (unless these variables have been assigned values in environment supplied by whatever invoked this script). Furthermore, since the = is quoted in both of these statements, these are not assignment statements; they are attempts to invoke a command named by the entirety of that quoted string after variable substitution and command substitution have been performed.

The commands:
Code:
     if [ ! -z $var2Value01] ; then
and
     if [ ! -z $var2Value01] ; then

both contain syntax errors (there must be a break (normally a <space> character) before the closing square bracket (]) in a test command. And, again, nothing in this script defines either of the variables that are being tested in these if statements.
This User Gave Thanks to Don Cragun For This Post:
# 4  
Old 02-12-2017
I can honestly say I have no idea what you are trying to do.
There are many errors:-
Code:
"$var2Value01=$(command 01)"
"$var2Value02=$(command 02)"

Should be:-
Code:
var2Value01=$(command 01)
var2Value02=$(command 02)

Should the "Value01" and "Value02" parts read the same as your array values?
Where is var2 used?
The square brackets "]" should have a space before them " ]".
Your "if then else" conditions make no sense as they are both identical except for the one line, echo $var2Value01 > file-$var2Value02.err . This would end up with two identical error files.
This User Gave Thanks to wisecracker For This Post:
# 5  
Old 02-12-2017
Hello,

Basically the above script supposed to be a short version of:
Code:
#!/bin/bash

     mkdir value1
     mkdir value2
     mkdir value3
     
     value1Value01=$(command 01 value1)
     value1Value02=$(command 02 value1)

     value2Value01=$(command 01 value2)
     value2Value02=$(command 02 value2)
     
     value3Value01=$(command 01 value3)
     value3Value02=$(command 02 value3)
     
     if [ ! -z value1Value01 ] ; then
          echo value1Value01 > file-value1Value01.err
     else
          echo "No errors in value1Value01"
     fi

     if [ ! -z value1Value02 ] ; then
          echo value1Value02 > file-value1Value02.err
     else
          echo "No errors in value1Value02"
     fi

     if [ ! -z value2Value01 ] ; then
          echo value2Value01 > file-value2Value01.err
     else
          echo "No errors in value2Value01"
     fi

     if [ ! -z value2Value02 ] ; then
          echo value2Value02 > file-value2Value02.err
     else
          echo "No errors in value2Value02"
     fi

     if [ ! -z value3Value01 ] ; then
          echo value3Value01 > file-value3Value01.err
     else
          echo "No errors in value3Value01"
     fi

     if [ ! -z value3Value02 ] ; then
          echo value3Value02 > file-value3Value02.err
     else
          echo "No errors in value3Value02"
     fi

done

I need to store the shell command results into a new variable and check if is empty,if not empty output to a file file-valueXValue0Y.err.

Code:
     
"$var2Value01=$(command 01)"
"$var2Value02=$(command 02)"

The output of the next shell commands
Code:
command 01

and
Code:
command 02

supposed to be assigned to the above variables.

Don Cragun and wisecracker are correct regarding the test commands and I have adjusted them in the detailed code.

Hopefully this time, I managed to give a better picture of what I'm trying to achieve.
# 6  
Old 02-12-2017
Quote:
Originally Posted by alex2005
I imagine the problem with this script is when assigning the dynamic variables
Code:
"$var2Value01=$(command 01)"

and
Code:
"$var2Value02=$(command 02)"

Does anyone had similar issues, and if yes how can this be solved?
Using bash you can try:

Code:
declare ${var2}Value01=$(command 01)
declare ${var2}Value02=$(command 02)

or

Code:
printf -v ${var2}Value01 "%s" $(command 01)
printf -v ${var2}Value02 "%s" $(command 02)


These variables can then be referenced using bash indirect expansion like this:

Code:
varname1=${var2}Value01

if [ ! -z ${!varname1} ] ; then
     echo ${!varname1} > file-${!varname1}.err
else
     echo "No errors in $varname1"
fi


Last edited by Chubler_XL; 02-12-2017 at 09:50 PM..
These 2 Users Gave Thanks to Chubler_XL For This Post:
# 7  
Old 02-13-2017
This is a demonstration longhand using 'eval' OSX 10.12.3, default bash terminal.
It shows how to create a new variable on the fly and how to extract its contents:-
Code:
Last login: Mon Feb 13 09:41:28 on ttys000
AMIGA:amiga~> var1="value1"
AMIGA:amiga~> eval "$var1"Value01=$( echo "MYVALUE1" )
AMIGA:amiga~> echo 'New _dynamic_ variable is '"$var1"'Value01...'
New _dynamic_ variable is value1Value01...
AMIGA:amiga~> echo "Transferred data to new variable is $value1Value01..."
Transferred data to new variable is MYVALUE1...
AMIGA:amiga~> _

Hope this is helpful as a starter...

Remember 'eval' is a _dangerous_ command to use...

Last edited by wisecracker; 02-13-2017 at 05:56 AM.. Reason: Add the last line.
This User Gave Thanks to wisecracker For This Post:
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Dummies Questions & Answers

Dynamic Variable creation

I am trying to create some variables based on the input by the user, say if user entered 3 then 3 variables and if 5 then 5 variables. I am using a for loop for (( i=1; i <= $num; i++ )) do x="num" x+=$i done When i am using echo $x it will show num1 but now how to create variables... (3 Replies)
Discussion started by: Raj999
3 Replies

2. Shell Programming and Scripting

Passing dynamic variable within another variable.

I have a small program which needs to pass variable dynamically to form the name of a second variable whose value wil be passed on to a third variable. ***************** Program Start ****************** LOC1=/loc1 PAT1IN=/loc2 PAT2IN=/loc3 if ; then for fpattern in `cat... (5 Replies)
Discussion started by: Cyril Jos
5 Replies

3. Shell Programming and Scripting

Bash, Dynamic Variable Problem >.<

Hello, I have a problem with a bash script, I've been doing recherches but i can't make it work. It is my first time with a dynamic variable and i don't understand how to write it. #!/bin/bash USER=BARSPIN HOTKEYS_PATH="/home/$USER/Documents/bash/tibia/HOTKEYS" CFG1="A" CFG2="B"... (5 Replies)
Discussion started by: barspin
5 Replies

4. Shell Programming and Scripting

Dynamic Variable in Linux

Hi All, I am trying declare variables at runtime to use them for some calculation. What im doing is to try and run a bunch of sql queries in round-robbin fashion for few times. So im trying to create a different variable for each SQL file using the file name to keep track of the total time of... (5 Replies)
Discussion started by: gemi
5 Replies

5. Shell Programming and Scripting

Dynamic file name in variable

Hi guys. i have a requirment as below. I have a scripts which perform for loop for i in /backup/logs -- it will give all the logs file SC_RIO_RWVM_20120413064217303.LOG SC_RIO_RWXM_20120413064225493.LOG SC_RIO_RXXM_20120413064233273.LOG ... do open script.sh ---- in this file... (3 Replies)
Discussion started by: guddu_12
3 Replies

6. Shell Programming and Scripting

dynamic variable value assignmnet

QUERY IN BRIEF Listing the query in short #! /bin/csh -f #say i have invoked the script with two arguments : a1 and 2 set arg = $1 # that means arg = a1 echo "$arg" #it prints a1 #now what i want is: echo "$a1" #it will give error message :a1 undefined. #however what i need is that the... (2 Replies)
Discussion started by: animesharma
2 Replies

7. Shell Programming and Scripting

Help with Dynamic variable

I need some variable help TEMP1=Jane TEMP2=Sue X=1 eval USER=TEMP${X} echo $USER This gives output USER1 I would like to get Jane I have tried eval USER='TEMP${X}' eval USER="TEMP${X}" eval USER=`TEMP${X}` (3 Replies)
Discussion started by: Jotne
3 Replies

8. Shell Programming and Scripting

Dynamic variable assignment

Hi all, I’m very new to UNIX programming. I have a question on dynamic variable 1. I’m having delimited file (only one row). First of all, I want to count number of columns based on delimiter. Then I want to create number of variables equal to number of fields. Say number of... (5 Replies)
Discussion started by: mkarthykeyan
5 Replies

9. Shell Programming and Scripting

dynamic variable name

I found one post in another site with a solution for my problem the below solution should explain what I want. #!/bin/sh first="one" second="two" third="three" myvar="first" echo ${!myvar} But this gives error 'bad substitution' System info SunOS sundev2 5.9... (3 Replies)
Discussion started by: johnbach
3 Replies

10. UNIX for Dummies Questions & Answers

Dynamic variable values

Bit of a newbie :D with regard to unix scripting and need some advice. Hopefully someone can help with the following: I have a predefined set of variables as follows: AAA_IP_ADD=1.1.1.1 BBB_IP_ADD=2.2.2.2 I have a funnction call which retrieves a value into $SUPPLIER which would be... (3 Replies)
Discussion started by: ronnie_uk
3 Replies
Login or Register to Ask a Question