Home > database >  Bash - Expand variable references in variables read via while read loop
Bash - Expand variable references in variables read via while read loop

Time:09-03

Bash version : 5.0.3(1)-ui-release

I don't know where I'm wrong.

1. One file "install_options.sh" with variables inside, like :

ADMIN_EMAIL="[email protected]"                               
ADMIN_FIRST_NAME="John"                                                  
ADMIN_NAME="Doe" 
....

2. another file : "admin_settings.txt" with data like "KEY VALUE" (withespace separator), and few value is variable:

KEY VALUE
KEY "${ADMIN_EMAIL}"
NEED_HELP PLEASE
KEY "${ADMIN_FIRST_NAME}"
...

3. When i try on cli:

$ echo "${ADMIN_EMAIL}"

I have the right output:

[email protected]

4. I try to use while read loop:

#!/bin/bash

while read IFS= -r KEY VALUE; do
 
COMMAND $KEY "${VALUE}"
 
done < admin_settings.txt

I get output:

KEY "${ADMIN_EMAIL}"

I would like get the output with the value:

KEY [email protected]

I have tried many things, like put source file inside the while read loop, but not working:

#!/bin/bash

while read IFS= -r KEY VALUE; 
do
   source install_options.sh
   COMMAND $KEY "${VALUE}"

done < admin_settings.txt

Inside "admin_settings.txt", I have tried with:

KEY "${ADMIN_EMAIL}"
KEY ${ADMIN_EMAIL}
KEY "$ADMIN_EMAIL"
KEY $ADMIN_EMAIL

Same with COMMAND inside while loop, I have tried:

COMMAND $KEY "${VALUE}" 
COMMAND $KEY ${VALUE} 
COMMAND $KEY "$VALUE"
COMMAND $KEY $VALUE

What can I do to get the expected output?

CodePudding user response:

Assuming that admin_settings.txt is EXACTLY in the following format (no shebang, no blank lines, no comments, no double-quotes around variables, etc...):

KEY0 VALUE0
KEY1 $ADMIN_EMAIL
NEED_HELP PLEASE
KEY2 $ADMIN_FIRST_NAME

Then you can use envsubst for substituting the variables with their value:

set -a
source install_options.sh
set  a

envsubst < admin_settings.txt |
while IFS=' ' read -r key val
do
    COMMAND "$key" "$val"
done

CodePudding user response:

In this setup i cant use envsubst , but i just found another way with for loop and arrays, like :

source install_options.sh

VALUE=("$ADMIN_EMAIL" "$ADMIN_FIRST_NAME" "$ADMIN_NAME") 
KEY=("KEY0" "KEY1" "KEY2_TANKS_FOR_YOUR_REPPLY")    

for (( z=0; z<${#VALUE[@]}; z   )); do

    COMMAND ${KEY[$z]} ${VALUE[$z]}

done
  • Related