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.
Latest posts by Surendra Anne (see all)
- Docker: How to copy files to/from docker container - June 30, 2020
- Anisble: ERROR! unexpected parameter type in action:
Fix - June 29, 2020 - FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018