Dynamic variable in bash

December 2016




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 :

This document entitled « Dynamic variable in bash » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.