Sujet : Re: create variables in a loop?
De : janis_papanagnou+ng (at) *nospam* hotmail.com (Janis Papanagnou)
Groupes : comp.unix.shellDate : 29. May 2024, 17:25:11
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v37ktf$17c89$1@dont-email.me>
References : 1
User-Agent : Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Thunderbird/45.8.0
On 29.05.2024 12:57, Dr Eberhard W Lisse wrote:
Hi,
I would like to do something like
for i in USD GBP
do
$i=somevalue
done
does not work, of course.
Any idea on how to create (and fill variables through a loop)?
You've already got the technical answer to your (literal) question.
Basically something like
for currency in USD GBP EUR
do
eval "${currency}='some value $((++n))'"
done
printf "%s\n" "$USD" "$GBP" "$EUR"
But I suggest to reconsider your software design approach!
Mind that variables are for programmers, and that if you create
variable names dynamically you either have to hard code the names
in several places, or use 'eval' in several places; where ever you
want to access them. (Which requires additional tests, to be sure.)
Other approaches are (for example) defining data structures for
the allowed variable name values (and attributes)
currencies=( USD GBP EUR )
factor=( 1.2 1.5 1.0 )
value=4.3
for (( i = 0; i < ${#currencies[@]} ; i++ ))
do
printf "%s: %g\n" "${currencies[i]}" $(( ${value} * ${factor[i]} ))
done
or use control constructs (to differentiate interrogated dynamic
name values) like
for f in data_file_*
do
curr=${f##data_file_}
case ${curr} in
(USD) val=1.2 ;;
(GBP) val=1.5 ;;
(EUR) val=1.0 ;;
(*) exit 1 ;;
esac
done
to be able to tell apart allowed values from undefined and errors.
The question is; do I really want an *individual* _variable name_
created? (Or is the technical [variable] name actually just data?)
Janis
greetings, el