Shell script: while variable concatenation


Shell script: while variable concatenation



This is my straightforward function:


generate_post_data()
{
cat <<-EOF
{"stringData": {}}
EOF
}



This is my other function:


generate_curl_body()
{
template=$(generate_post_data $secret_id)
echo "$template"
echo "$KVS_VARIABLES" | while read -r key value
do
template=$(echo "$template" | jq ".stringData += { "$key" : "$value" }")
echo $template
done
}



The output is:


#Before while -> {"stringData": {}}
#1 iteration -> { "stringData": { "VAR1": "VAL1" } }
#2 iteration -> { "stringData": { "VAR1": "VAL1", "VAR2": "VAL2" } }
#3 iteration -> { "stringData": { "VAR1": "VAL1", "VAR2": "VAL2", "VAR3": "VAL3" } }
#After while -> {"stringData": {}}



Why template variable is not filled?


template





Possible duplicate of Left side of pipe is the subshell?
– Anthony Geoghegan
Jul 2 at 10:43






Possible duplicate of A variable modified inside a while loop is not remembered
– Biffen
Jul 2 at 10:47




1 Answer
1



It is not filled because the | while is executed in subshell. From the manual page of Bash (for example):


| while



Each command in a pipeline is executed as a separate process (i.e., in a subshell).



If the shell is Bash, the easy fix is to replace the echo "$KVS_VARIABLES" | with a here-string:


echo "$KVS_VARIABLES" |


while read -r key value; do
template=$(echo "$template" | jq ".stringData += { "$key" : "$value" }")
echo $template
done <<< "$KVS_VARIABLES"



If your shell does not accept here-strings, you can always wrap the while in a compound command { while ... done; echo "$template"; } and use an extra command substitution:


while


{ while ... done; echo "$template"; }


template="$(
echo "$KVS_VARIABLES" |
{
while read -r key value; do
template=$(
echo "$template" |
jq ".stringData += { "$key" : "$value" }"
)
done
echo "$template"
}
)"





I'm using !/usr/bin/env sh. I'm getting this error message: Syntax error: redirection unexpected
– Jordi
Jul 2 at 10:53


!/usr/bin/env sh


Syntax error: redirection unexpected





Showed a fix which should work for /bin/sh.
– AlexP
Jul 2 at 11:14


/bin/sh






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to make file upload 'Required' in Contact Form 7?

Rothschild family

amazon EC2 - How to make wp-config.php to writable?