I have inherited a shell script which has following code
while IFS='=' read -r key value
do
# echo "key ${key}"
if [[ ${key} =~ ^# ]]; then
# echo "comment line ${key}, skipping....."
continue
fi
eval ${key}=\${value}
echo "key: ${key}, value: ${value}"
done <kafka-parameters.txt
where kafka-parameters.txt file contains entries like below
#Schema Registry
DEV_SR_URLS=http://sr1-dev:8081, http://sr2-dev:8081
QA_SR_URLS=http://sr1-qa:8081, http://sr2-qa:8081
STAGE_SR_URLS=http://sr1-qa:8081, http://sr2-qa:8081
PROD_SR_URLS=http://sr1:8081, http://sr2:8081
#
#Bootstrap Servers
DEV_BOOTSTRAP_SERVERS=broker1-dev:9092,broker2-dev:9092,broker3-dev:9092
QA_BOOTSTRAP_SERVERS=broker1-qa:9092,broker2-qa:9092,broker3-qa:9092
STAGE_BOOTSTRAP_SERVERS=broker1-qa:9092,broker2-qa:9092,broker3-qa:9092
PROD_BOOTSTRAP_SERVERS=broker1:9092,broker2:9092,broker3:9092
#
In the above snippet, what is the purpose of "\" before ${value} ?
From my understanding eval ${key}=${value}
creates a variable of name ${key} and assigns value of ${value} to it and eval makes that assignment available after the loop.
Is this correct? Still do not understand the purpose of \${value}
or what is difference between
eval ${key}=\${value}
and
eval ${key}=${value}
Thank you
CodePudding user response:
Consider the following assignment:
value="foo bar"
key=$value
This will work, because the right-hand side doesn't undergo word-splitting; the name key
will get the value foo bar
.
Now consider
key=foo
$key=$value
This is just an error, because it's not an assignment; it's an attempt, after parameter expansion and word-splitting, to run a command name foo=foo
with an argument bar
.
Using eval
, we choose to let some expansions happen befor eval
runs, and some to happen after. With
eval $key=\${value}
eval
will see the string foo=${value}
, which it will execute by expanding $value}
and assigning the entire result to foo
, similar to the first example above.
However, if you let both parameters expand first,
eval $key=${value}
then after parameter expansion eval
gets two arguments, key=foo
and bar
, which results in a command named bar
being executed with key=foo
in its environment.