Q. I am getting "command not found" error when doing dynimic variable assignemet in Shell scripts. How can I resolve this issue?

 

Let use replicate this issue.

#!/bin/bash
VAR1=abc
i=0
VAR$i=$VAR1
echo "Value of VAR0 is $VAR0"

Save this file and execute this script.
bash abc.sh

abc.sh: line 4: VAR0=abc: command not found

Value of VAR0 is

If you see I am getting command not found error.

This is due to the line VAR$i=$VAR1, in which we are trying to substitute two variable at a time, one on RHS and other on LHS. This is not possible by default in Shell scripting. First we have to substitute "i" value then substitute $VAR1 value. To resolve this issue we have to use eval command which gives us second chance to execute a command.

Modified version of above script as below.

#!/bin/bash
VAR1=abc
i=0
eval VAR$i=$VAR1
echo "VAlue of VAR0 is $VAR0"

Output:

bash abc.sh

VAlue of VAR0 is abc

Hope this helps to resolve dynamic assignmet of variables.

 

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.