Dynamic variable in bash

March 2017




Issue


I want to save the result of a function in a variable:
idents=(a b c);  
count=${#idents[*]};  
for ((i=0; i < $count; i++)); do  
    ident=${idents[${i}]};  
    ${ident}=${i};  
done


I had like that either adds the variables $ a, $ b, $ c with the values 0, 1, 2

Solution


This is the solution:

#! /bin/bash 
#set -xv 

idents=(a b c); 
count=${#idents[*]}; 
for ((i=0; i < $count; i++)); do 
        ident=${idents[${i}]}; 
        eval "${ident}=${i}"; 
done 
echo "${idents[0]} = $a" 
echo "${idents[1]} = $b" 
echo "${idents[2]} = $c" 

$ sh foo.sh 
a = 0 
b = 1 
c = 2

Note


Thanks to jipicy for this tip on the forum.

Related


Published by aakai1056.
This document, titled "Dynamic variable in bash," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (ccm.net).