Home > Software design >  How to assign value to a variable that is provided from file in for loop
How to assign value to a variable that is provided from file in for loop

Time:11-07

Im facing a problem with assigning a value to a variable that its name is stored in other variable or a file

cat ids.txt

ID1
ID2
ID3

What i want to do is:

for i in `cat ids.txt'; do $i=`cat /proc/sys/kernel/random/uuid`

or

for i in ID1 ID2 ID3; do $i=`cat /proc/sys/kernel/random/uuid`

But its not working. What i would like to have, its something like:

echo $ID1
5dcteeee-6abb-4agg-86bb-948593020451
echo $ID2
5dcteeee-6abb-4agg-46db-948593322990
echo $ID3
5dcteeee-6abb-4agg-86cb-948593abcd45

CodePudding user response:

Use declare. https://linuxcommand.org/lc3_man_pages/declareh.html

# declare values
for i in ID1 ID2 ID3; do
  declare ${i}=$(cat /proc/sys/kernel/random/uuid)
done

# read values (note the `!` in the variable to simulate "$ID1", not ID1)
for i in ID1 ID2 ID3; do echo ${!i}; done

3f204128-bac6-481e-abd3-37bb6cb522da
ccddd0fb-1b6c-492e-bda3-f976ca62d946
ff5e04b9-2e51-4dac-be41-4c56cfbce22e

Or better yet... Reading IDs from the file:

for i in $(cat ids.txt); do
  echo "ID from file: ${i}"
  declare ${i}=$(cat /proc/sys/kernel/random/uuid)
  echo "${i}=${!i}"
done

Result:

$ cat ids.txt
ID1
ID2
ID3

$ for i in $(cat ids.txt); do echo "ID from file: ${i}"; declare ${i}=$(cat /proc/sys/kernel/random/uuid); echo "${i}=${!i}"; done
ID from file: ID1
ID1=d5c4a002-9039-498b-930f-0aab488eb6da
ID from file: ID2
ID2=a77f6c01-7170-4f4f-a924-1069e48e93db
ID from file: ID3
ID3=bafe8bb2-98e6-40fa-9fb2-0bcfd4b69fad
  • Related