Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign value to a variable that is provided from file in for loop

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading