Thursday, December 13, 2012

bash variable assignment "command not found" error

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 try to substitue 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 substitue "i" value then substitue $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.



 

0 comments:

Post a Comment