0
Thanks

A few words of thanks would be greatly appreciated.

Dynamic variable in bash




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
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

Thanks to jipicy for this tip on the forum.
0
Thanks

A few words of thanks would be greatly appreciated.

Ask a question
CCM is a leading international tech website. Our content is written in collaboration with IT experts, under the direction of Jean-François Pillou, founder of CCM.net. CCM reaches more than 50 million unique visitors per month and is available in 11 languages.
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).

0 Comments