Iterate through multiline string line by line Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Community Moderator Election Results Why I closed the “Why is Kali so hard” questionWhy is printf better than echo?Why is using a shell loop to process text considered bad practice?Are there naming conventions for variables in shell scripts?Why is my variable local in one 'while read' loop, but not in another seemingly similar loop?Understanding IFSWhat should interactive shells do in orphaned process groups?for loop to iterate through some file nth positionCron only occasionally sends e-mail on output and errorsIterate Through Sets of Command Arguments in Bashhow to iterate through files in directory excluding hidden filesStarting an interactive shell as an asynchronous process (signal delivery)Control characters in a terminal with an active foreground processhow to let sudo fork bash instead of sh?Multiline command : comment out one line

Statistical model of ligand substitution

Why is "Captain Marvel" translated as male in Portugal?

Single author papers against my advisor's will?

Mortgage adviser recommends a longer term than necessary combined with overpayments

Why don't the Weasley twins use magic outside of school if the Trace can only find the location of spells cast?

Antler Helmet: Can it work?

Estimated State payment too big --> money back; + 2018 Tax Reform

Can a monk deflect thrown melee weapons?

Area of a 2D convex hull

Blender game recording at the wrong time

How should I respond to a player wanting to catch a sword between their hands?

What did Darwin mean by 'squib' here?

Array/tabular for long multiplication

Should you tell Jews they are breaking a commandment?

Can a zero nonce be safely used with AES-GCM if the key is random and never used again?

Did the new image of black hole confirm the general theory of relativity?

Why does this iterative way of solving of equation work?

Losing the Initialization Vector in Cipher Block Chaining

Was credit for the black hole image misattributed?

What's the difference between (size_t)-1 and ~0?

Why is there no army of Iron-Mans in the MCU?

Working around an AWS network ACL rule limit

What's the point in a preamp?

Fishing simulator



Iterate through multiline string line by line



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
2019 Community Moderator Election Results
Why I closed the “Why is Kali so hard” questionWhy is printf better than echo?Why is using a shell loop to process text considered bad practice?Are there naming conventions for variables in shell scripts?Why is my variable local in one 'while read' loop, but not in another seemingly similar loop?Understanding IFSWhat should interactive shells do in orphaned process groups?for loop to iterate through some file nth positionCron only occasionally sends e-mail on output and errorsIterate Through Sets of Command Arguments in Bashhow to iterate through files in directory excluding hidden filesStarting an interactive shell as an asynchronous process (signal delivery)Control characters in a terminal with an active foreground processhow to let sudo fork bash instead of sh?Multiline command : comment out one line



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I would like to process a multiline string and iterate it line by line, in a POSIX shell (/bin/sh) on a BSD platform. Bash is not included in the base BSD-distribution and has a GPL license - so I am trying to make it universally work with /bin/sh instead.



I found a solution using a pipe, however in the regular /bin/sh shell, these a processed in a separate process, meaning the following does not work:



MULTILINE="`cat $SOMEFILE`"
SOMEVAR="original value"

echo "$MULTILINE" | while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
echo "this is a single line: $SINGLELINE"
echo "SOMEVAR is now: $SOMEVAR"
done

echo "Final SOMEVAR is unchanged: $SOMEVAR"


In the above example, it accomplishes what I want, except for the fact that changes to variables such as $SOMEVAR are not accessible outside the while loop.



My question: how can I accomplish something like the above without this restriction? Note that many solutions require Bash, whereas I am using the standard POSIX-shell /bin/sh.










share|improve this question
























  • Why can you not use bash? (add to your question)

    – ctrl-alt-delor
    Mar 31 at 10:54











  • I can not reproduce your issue using /bin/sh on a BSD system. There is nothing in this code that would require bash.

    – Kusalananda
    Mar 31 at 10:57












  • My apologies. In trying to create a minimized sample of the actual issue, i made some errors. I updated the code sample now, and it should reflect the problem correctly now. The example indeed does not require Bash.

    – Steiner
    Mar 31 at 11:09











  • @Steiner In fact, it would have the same issue in bash.

    – Kusalananda
    Mar 31 at 11:21






  • 3





    There is no Bourne shell on the BSDs. Nor is the Bourne shell standard. Do not conflate the Bourne shell with a POSIX-conformant sh.

    – JdeBP
    Mar 31 at 11:29

















2















I would like to process a multiline string and iterate it line by line, in a POSIX shell (/bin/sh) on a BSD platform. Bash is not included in the base BSD-distribution and has a GPL license - so I am trying to make it universally work with /bin/sh instead.



I found a solution using a pipe, however in the regular /bin/sh shell, these a processed in a separate process, meaning the following does not work:



MULTILINE="`cat $SOMEFILE`"
SOMEVAR="original value"

echo "$MULTILINE" | while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
echo "this is a single line: $SINGLELINE"
echo "SOMEVAR is now: $SOMEVAR"
done

echo "Final SOMEVAR is unchanged: $SOMEVAR"


In the above example, it accomplishes what I want, except for the fact that changes to variables such as $SOMEVAR are not accessible outside the while loop.



My question: how can I accomplish something like the above without this restriction? Note that many solutions require Bash, whereas I am using the standard POSIX-shell /bin/sh.










share|improve this question
























  • Why can you not use bash? (add to your question)

    – ctrl-alt-delor
    Mar 31 at 10:54











  • I can not reproduce your issue using /bin/sh on a BSD system. There is nothing in this code that would require bash.

    – Kusalananda
    Mar 31 at 10:57












  • My apologies. In trying to create a minimized sample of the actual issue, i made some errors. I updated the code sample now, and it should reflect the problem correctly now. The example indeed does not require Bash.

    – Steiner
    Mar 31 at 11:09











  • @Steiner In fact, it would have the same issue in bash.

    – Kusalananda
    Mar 31 at 11:21






  • 3





    There is no Bourne shell on the BSDs. Nor is the Bourne shell standard. Do not conflate the Bourne shell with a POSIX-conformant sh.

    – JdeBP
    Mar 31 at 11:29













2












2








2








I would like to process a multiline string and iterate it line by line, in a POSIX shell (/bin/sh) on a BSD platform. Bash is not included in the base BSD-distribution and has a GPL license - so I am trying to make it universally work with /bin/sh instead.



I found a solution using a pipe, however in the regular /bin/sh shell, these a processed in a separate process, meaning the following does not work:



MULTILINE="`cat $SOMEFILE`"
SOMEVAR="original value"

echo "$MULTILINE" | while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
echo "this is a single line: $SINGLELINE"
echo "SOMEVAR is now: $SOMEVAR"
done

echo "Final SOMEVAR is unchanged: $SOMEVAR"


In the above example, it accomplishes what I want, except for the fact that changes to variables such as $SOMEVAR are not accessible outside the while loop.



My question: how can I accomplish something like the above without this restriction? Note that many solutions require Bash, whereas I am using the standard POSIX-shell /bin/sh.










share|improve this question
















I would like to process a multiline string and iterate it line by line, in a POSIX shell (/bin/sh) on a BSD platform. Bash is not included in the base BSD-distribution and has a GPL license - so I am trying to make it universally work with /bin/sh instead.



I found a solution using a pipe, however in the regular /bin/sh shell, these a processed in a separate process, meaning the following does not work:



MULTILINE="`cat $SOMEFILE`"
SOMEVAR="original value"

echo "$MULTILINE" | while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
echo "this is a single line: $SINGLELINE"
echo "SOMEVAR is now: $SOMEVAR"
done

echo "Final SOMEVAR is unchanged: $SOMEVAR"


In the above example, it accomplishes what I want, except for the fact that changes to variables such as $SOMEVAR are not accessible outside the while loop.



My question: how can I accomplish something like the above without this restriction? Note that many solutions require Bash, whereas I am using the standard POSIX-shell /bin/sh.







shell






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 31 at 11:44







Steiner

















asked Mar 31 at 10:52









SteinerSteiner

908




908












  • Why can you not use bash? (add to your question)

    – ctrl-alt-delor
    Mar 31 at 10:54











  • I can not reproduce your issue using /bin/sh on a BSD system. There is nothing in this code that would require bash.

    – Kusalananda
    Mar 31 at 10:57












  • My apologies. In trying to create a minimized sample of the actual issue, i made some errors. I updated the code sample now, and it should reflect the problem correctly now. The example indeed does not require Bash.

    – Steiner
    Mar 31 at 11:09











  • @Steiner In fact, it would have the same issue in bash.

    – Kusalananda
    Mar 31 at 11:21






  • 3





    There is no Bourne shell on the BSDs. Nor is the Bourne shell standard. Do not conflate the Bourne shell with a POSIX-conformant sh.

    – JdeBP
    Mar 31 at 11:29

















  • Why can you not use bash? (add to your question)

    – ctrl-alt-delor
    Mar 31 at 10:54











  • I can not reproduce your issue using /bin/sh on a BSD system. There is nothing in this code that would require bash.

    – Kusalananda
    Mar 31 at 10:57












  • My apologies. In trying to create a minimized sample of the actual issue, i made some errors. I updated the code sample now, and it should reflect the problem correctly now. The example indeed does not require Bash.

    – Steiner
    Mar 31 at 11:09











  • @Steiner In fact, it would have the same issue in bash.

    – Kusalananda
    Mar 31 at 11:21






  • 3





    There is no Bourne shell on the BSDs. Nor is the Bourne shell standard. Do not conflate the Bourne shell with a POSIX-conformant sh.

    – JdeBP
    Mar 31 at 11:29
















Why can you not use bash? (add to your question)

– ctrl-alt-delor
Mar 31 at 10:54





Why can you not use bash? (add to your question)

– ctrl-alt-delor
Mar 31 at 10:54













I can not reproduce your issue using /bin/sh on a BSD system. There is nothing in this code that would require bash.

– Kusalananda
Mar 31 at 10:57






I can not reproduce your issue using /bin/sh on a BSD system. There is nothing in this code that would require bash.

– Kusalananda
Mar 31 at 10:57














My apologies. In trying to create a minimized sample of the actual issue, i made some errors. I updated the code sample now, and it should reflect the problem correctly now. The example indeed does not require Bash.

– Steiner
Mar 31 at 11:09





My apologies. In trying to create a minimized sample of the actual issue, i made some errors. I updated the code sample now, and it should reflect the problem correctly now. The example indeed does not require Bash.

– Steiner
Mar 31 at 11:09













@Steiner In fact, it would have the same issue in bash.

– Kusalananda
Mar 31 at 11:21





@Steiner In fact, it would have the same issue in bash.

– Kusalananda
Mar 31 at 11:21




3




3





There is no Bourne shell on the BSDs. Nor is the Bourne shell standard. Do not conflate the Bourne shell with a POSIX-conformant sh.

– JdeBP
Mar 31 at 11:29





There is no Bourne shell on the BSDs. Nor is the Bourne shell standard. Do not conflate the Bourne shell with a POSIX-conformant sh.

– JdeBP
Mar 31 at 11:29










3 Answers
3






active

oldest

votes


















4














You could use a here document:



while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
printf '%sn' "this is a single line: $SINGLELINE"
printf '%sn' "SOMEVAR is now: $SOMEVAR"
done << EOF
$MULTILINE
EOF
printf '%sn' "Final SOMEVAL is still $SOMEVAR"


Depending on the sh implementation, here-documents are implemented either as a deleted temporary file where the shell has stored the expansion of the variable followed by newline beforehand, or a pipe to which the shell feeds the expansion of the variable followed by newline. But in either case, except in the original Bourne shell (a shell that is no longer in use these days and is not a POSIX compliant shell), the command being redirected is not run in a subshell (as POSIX requires).



or you could use split+glob:



IFS='
' # split on newline only
set -o noglob
for SINGLELINE in $MULTILINE
do
SOMEVAR="updated value"
printf '%sn' "this is a single line: $SINGLELINE"
printf '%sn' "SOMEVAR is now: $SOMEVAR"
done
printf '%sn' "Final SOMEVAL is still $SOMEVAR"


But beware it skips empty lines.






share|improve this answer

























  • Both solutions worked well for me with /bin/sh. I think this solution is better than the one Kusalananda provided, though his answer is very informative too. I particularly like the for-loop solution since it probably is faster because it does not use read which is very slow. Thanks!

    – Steiner
    Mar 31 at 15:54











  • @Steiner (Just had to quickly double check so that I didn't have a for-loop solution, which I fortunately did not have)

    – Kusalananda
    Mar 31 at 18:41



















3














You would read directly from the file without the pipeline. This avoids running the while loop in a subshell, which allows you to see the changed value of $SOMEVALUE after the loop.



SOMEVAR="original value"

while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
printf 'this is a single line: %sn' "$SINGLELINE"
printf 'SOMEVAR is now: %sn' "$SOMEVAR"
done <"$SOMEFILE"

printf 'Final SOMEVAR is: %sn' "$SOMEVAR"


If you insist on having your $MULTILINE variable, then write that to a file and read it from there:



tmpfile=$(mktemp)
printf '%sn' "$MULTILINE" >"$tmpfile"

while ...; do
...
done <"$tmpfile"
rm "$tmpfile"


Also related:



  • Why is my variable local in one 'while read' loop, but not in another seemingly similar loop?

An answer to the above linked question also suggests writing your program in such a way that all uses of $SOMEVAR occurs within the subshell at the end of the pipeline:



MULTILINE=$(cat "$SOMEFILE")
SOMEVAR="original value"

printf '%sn' "$MULTILINE" |
while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
printf 'this is a single line: %sn' "$SINGLELINE"
printf 'SOMEVAR is now: %sn' "$SOMEVAR"
done

printf 'Final SOMEVAR is: %sn' "$SOMEVAR"



Also possibly related:



  • Why is using a shell loop to process text considered bad practice?

Other questions that may be of interest:



  • Why is printf better than echo?

  • Are there naming conventions for variables in shell scripts?





share|improve this answer

























  • Indeed this works, but requires a file to be fed to the while-loop. My actual code is more complex, and requires a modified multiline string to be fed to the while-loop. Your solution to write this multiline string to a temporary file works, but is there a solution that does not require writing a temporary file?

    – Steiner
    Mar 31 at 11:28











  • @Steiner See update answer. There's not much else you could do without using features of specific shells.

    – Kusalananda
    Mar 31 at 11:33











  • Thank you that answers my question. The suggestion at the end and the links provided are very helpful too!

    – Steiner
    Mar 31 at 11:43











  • @Steiner ... except for using a here-document. Well, there's a thing I didn't think of :-)

    – Kusalananda
    Mar 31 at 18:42


















0














It works for me :



$ cat bin/test
#! /bin/sh
SOMEFILE=$1
MULTILINE="`cat $SOMEFILE`"
SOMEVAR="blah"

echo "$MULTILINE" | while IFS= read -r SINGLELINE
do
echo "this is a single line: $SINGLELINE"
echo "but accessing this var fails: $SOMEVAR"
done


and



$ bin/test bin/test
this is a single line: #! /bin/sh
but accessing this var fails: blah
this is a single line: SOMEFILE=$1
but accessing this var fails: blah
this is a single line: MULTILINE="`cat $SOMEFILE`"
but accessing this var fails: blah
this is a single line: SOMEVAR="blah"
but accessing this var fails: blah
this is a single line:
but accessing this var fails: blah
this is a single line: echo "$MULTILINE" | while IFS= read -r SINGLELINE
but accessing this var fails: blah
this is a single line: do
but accessing this var fails: blah
this is a single line: echo "this is a single line: $SINGLELINE"
but accessing this var fails: blah
this is a single line: echo "but accessing this var fails: $SOMEVAR"
but accessing this var fails: blah
this is a single line: done
but accessing this var fails: blah





share|improve this answer























  • My apologies. In trying to create a minimized sample of the actual issue, i made some errors. I updated the code sample now, and it should reflect the problem correctly now.

    – Steiner
    Mar 31 at 11:13











Your Answer








StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "106"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f509714%2fiterate-through-multiline-string-line-by-line%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









4














You could use a here document:



while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
printf '%sn' "this is a single line: $SINGLELINE"
printf '%sn' "SOMEVAR is now: $SOMEVAR"
done << EOF
$MULTILINE
EOF
printf '%sn' "Final SOMEVAL is still $SOMEVAR"


Depending on the sh implementation, here-documents are implemented either as a deleted temporary file where the shell has stored the expansion of the variable followed by newline beforehand, or a pipe to which the shell feeds the expansion of the variable followed by newline. But in either case, except in the original Bourne shell (a shell that is no longer in use these days and is not a POSIX compliant shell), the command being redirected is not run in a subshell (as POSIX requires).



or you could use split+glob:



IFS='
' # split on newline only
set -o noglob
for SINGLELINE in $MULTILINE
do
SOMEVAR="updated value"
printf '%sn' "this is a single line: $SINGLELINE"
printf '%sn' "SOMEVAR is now: $SOMEVAR"
done
printf '%sn' "Final SOMEVAL is still $SOMEVAR"


But beware it skips empty lines.






share|improve this answer

























  • Both solutions worked well for me with /bin/sh. I think this solution is better than the one Kusalananda provided, though his answer is very informative too. I particularly like the for-loop solution since it probably is faster because it does not use read which is very slow. Thanks!

    – Steiner
    Mar 31 at 15:54











  • @Steiner (Just had to quickly double check so that I didn't have a for-loop solution, which I fortunately did not have)

    – Kusalananda
    Mar 31 at 18:41
















4














You could use a here document:



while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
printf '%sn' "this is a single line: $SINGLELINE"
printf '%sn' "SOMEVAR is now: $SOMEVAR"
done << EOF
$MULTILINE
EOF
printf '%sn' "Final SOMEVAL is still $SOMEVAR"


Depending on the sh implementation, here-documents are implemented either as a deleted temporary file where the shell has stored the expansion of the variable followed by newline beforehand, or a pipe to which the shell feeds the expansion of the variable followed by newline. But in either case, except in the original Bourne shell (a shell that is no longer in use these days and is not a POSIX compliant shell), the command being redirected is not run in a subshell (as POSIX requires).



or you could use split+glob:



IFS='
' # split on newline only
set -o noglob
for SINGLELINE in $MULTILINE
do
SOMEVAR="updated value"
printf '%sn' "this is a single line: $SINGLELINE"
printf '%sn' "SOMEVAR is now: $SOMEVAR"
done
printf '%sn' "Final SOMEVAL is still $SOMEVAR"


But beware it skips empty lines.






share|improve this answer

























  • Both solutions worked well for me with /bin/sh. I think this solution is better than the one Kusalananda provided, though his answer is very informative too. I particularly like the for-loop solution since it probably is faster because it does not use read which is very slow. Thanks!

    – Steiner
    Mar 31 at 15:54











  • @Steiner (Just had to quickly double check so that I didn't have a for-loop solution, which I fortunately did not have)

    – Kusalananda
    Mar 31 at 18:41














4












4








4







You could use a here document:



while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
printf '%sn' "this is a single line: $SINGLELINE"
printf '%sn' "SOMEVAR is now: $SOMEVAR"
done << EOF
$MULTILINE
EOF
printf '%sn' "Final SOMEVAL is still $SOMEVAR"


Depending on the sh implementation, here-documents are implemented either as a deleted temporary file where the shell has stored the expansion of the variable followed by newline beforehand, or a pipe to which the shell feeds the expansion of the variable followed by newline. But in either case, except in the original Bourne shell (a shell that is no longer in use these days and is not a POSIX compliant shell), the command being redirected is not run in a subshell (as POSIX requires).



or you could use split+glob:



IFS='
' # split on newline only
set -o noglob
for SINGLELINE in $MULTILINE
do
SOMEVAR="updated value"
printf '%sn' "this is a single line: $SINGLELINE"
printf '%sn' "SOMEVAR is now: $SOMEVAR"
done
printf '%sn' "Final SOMEVAL is still $SOMEVAR"


But beware it skips empty lines.






share|improve this answer















You could use a here document:



while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
printf '%sn' "this is a single line: $SINGLELINE"
printf '%sn' "SOMEVAR is now: $SOMEVAR"
done << EOF
$MULTILINE
EOF
printf '%sn' "Final SOMEVAL is still $SOMEVAR"


Depending on the sh implementation, here-documents are implemented either as a deleted temporary file where the shell has stored the expansion of the variable followed by newline beforehand, or a pipe to which the shell feeds the expansion of the variable followed by newline. But in either case, except in the original Bourne shell (a shell that is no longer in use these days and is not a POSIX compliant shell), the command being redirected is not run in a subshell (as POSIX requires).



or you could use split+glob:



IFS='
' # split on newline only
set -o noglob
for SINGLELINE in $MULTILINE
do
SOMEVAR="updated value"
printf '%sn' "this is a single line: $SINGLELINE"
printf '%sn' "SOMEVAR is now: $SOMEVAR"
done
printf '%sn' "Final SOMEVAL is still $SOMEVAR"


But beware it skips empty lines.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 31 at 18:03

























answered Mar 31 at 13:42









Stéphane ChazelasStéphane Chazelas

314k57594953




314k57594953












  • Both solutions worked well for me with /bin/sh. I think this solution is better than the one Kusalananda provided, though his answer is very informative too. I particularly like the for-loop solution since it probably is faster because it does not use read which is very slow. Thanks!

    – Steiner
    Mar 31 at 15:54











  • @Steiner (Just had to quickly double check so that I didn't have a for-loop solution, which I fortunately did not have)

    – Kusalananda
    Mar 31 at 18:41


















  • Both solutions worked well for me with /bin/sh. I think this solution is better than the one Kusalananda provided, though his answer is very informative too. I particularly like the for-loop solution since it probably is faster because it does not use read which is very slow. Thanks!

    – Steiner
    Mar 31 at 15:54











  • @Steiner (Just had to quickly double check so that I didn't have a for-loop solution, which I fortunately did not have)

    – Kusalananda
    Mar 31 at 18:41

















Both solutions worked well for me with /bin/sh. I think this solution is better than the one Kusalananda provided, though his answer is very informative too. I particularly like the for-loop solution since it probably is faster because it does not use read which is very slow. Thanks!

– Steiner
Mar 31 at 15:54





Both solutions worked well for me with /bin/sh. I think this solution is better than the one Kusalananda provided, though his answer is very informative too. I particularly like the for-loop solution since it probably is faster because it does not use read which is very slow. Thanks!

– Steiner
Mar 31 at 15:54













@Steiner (Just had to quickly double check so that I didn't have a for-loop solution, which I fortunately did not have)

– Kusalananda
Mar 31 at 18:41






@Steiner (Just had to quickly double check so that I didn't have a for-loop solution, which I fortunately did not have)

– Kusalananda
Mar 31 at 18:41














3














You would read directly from the file without the pipeline. This avoids running the while loop in a subshell, which allows you to see the changed value of $SOMEVALUE after the loop.



SOMEVAR="original value"

while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
printf 'this is a single line: %sn' "$SINGLELINE"
printf 'SOMEVAR is now: %sn' "$SOMEVAR"
done <"$SOMEFILE"

printf 'Final SOMEVAR is: %sn' "$SOMEVAR"


If you insist on having your $MULTILINE variable, then write that to a file and read it from there:



tmpfile=$(mktemp)
printf '%sn' "$MULTILINE" >"$tmpfile"

while ...; do
...
done <"$tmpfile"
rm "$tmpfile"


Also related:



  • Why is my variable local in one 'while read' loop, but not in another seemingly similar loop?

An answer to the above linked question also suggests writing your program in such a way that all uses of $SOMEVAR occurs within the subshell at the end of the pipeline:



MULTILINE=$(cat "$SOMEFILE")
SOMEVAR="original value"

printf '%sn' "$MULTILINE" |
while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
printf 'this is a single line: %sn' "$SINGLELINE"
printf 'SOMEVAR is now: %sn' "$SOMEVAR"
done

printf 'Final SOMEVAR is: %sn' "$SOMEVAR"



Also possibly related:



  • Why is using a shell loop to process text considered bad practice?

Other questions that may be of interest:



  • Why is printf better than echo?

  • Are there naming conventions for variables in shell scripts?





share|improve this answer

























  • Indeed this works, but requires a file to be fed to the while-loop. My actual code is more complex, and requires a modified multiline string to be fed to the while-loop. Your solution to write this multiline string to a temporary file works, but is there a solution that does not require writing a temporary file?

    – Steiner
    Mar 31 at 11:28











  • @Steiner See update answer. There's not much else you could do without using features of specific shells.

    – Kusalananda
    Mar 31 at 11:33











  • Thank you that answers my question. The suggestion at the end and the links provided are very helpful too!

    – Steiner
    Mar 31 at 11:43











  • @Steiner ... except for using a here-document. Well, there's a thing I didn't think of :-)

    – Kusalananda
    Mar 31 at 18:42















3














You would read directly from the file without the pipeline. This avoids running the while loop in a subshell, which allows you to see the changed value of $SOMEVALUE after the loop.



SOMEVAR="original value"

while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
printf 'this is a single line: %sn' "$SINGLELINE"
printf 'SOMEVAR is now: %sn' "$SOMEVAR"
done <"$SOMEFILE"

printf 'Final SOMEVAR is: %sn' "$SOMEVAR"


If you insist on having your $MULTILINE variable, then write that to a file and read it from there:



tmpfile=$(mktemp)
printf '%sn' "$MULTILINE" >"$tmpfile"

while ...; do
...
done <"$tmpfile"
rm "$tmpfile"


Also related:



  • Why is my variable local in one 'while read' loop, but not in another seemingly similar loop?

An answer to the above linked question also suggests writing your program in such a way that all uses of $SOMEVAR occurs within the subshell at the end of the pipeline:



MULTILINE=$(cat "$SOMEFILE")
SOMEVAR="original value"

printf '%sn' "$MULTILINE" |
while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
printf 'this is a single line: %sn' "$SINGLELINE"
printf 'SOMEVAR is now: %sn' "$SOMEVAR"
done

printf 'Final SOMEVAR is: %sn' "$SOMEVAR"



Also possibly related:



  • Why is using a shell loop to process text considered bad practice?

Other questions that may be of interest:



  • Why is printf better than echo?

  • Are there naming conventions for variables in shell scripts?





share|improve this answer

























  • Indeed this works, but requires a file to be fed to the while-loop. My actual code is more complex, and requires a modified multiline string to be fed to the while-loop. Your solution to write this multiline string to a temporary file works, but is there a solution that does not require writing a temporary file?

    – Steiner
    Mar 31 at 11:28











  • @Steiner See update answer. There's not much else you could do without using features of specific shells.

    – Kusalananda
    Mar 31 at 11:33











  • Thank you that answers my question. The suggestion at the end and the links provided are very helpful too!

    – Steiner
    Mar 31 at 11:43











  • @Steiner ... except for using a here-document. Well, there's a thing I didn't think of :-)

    – Kusalananda
    Mar 31 at 18:42













3












3








3







You would read directly from the file without the pipeline. This avoids running the while loop in a subshell, which allows you to see the changed value of $SOMEVALUE after the loop.



SOMEVAR="original value"

while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
printf 'this is a single line: %sn' "$SINGLELINE"
printf 'SOMEVAR is now: %sn' "$SOMEVAR"
done <"$SOMEFILE"

printf 'Final SOMEVAR is: %sn' "$SOMEVAR"


If you insist on having your $MULTILINE variable, then write that to a file and read it from there:



tmpfile=$(mktemp)
printf '%sn' "$MULTILINE" >"$tmpfile"

while ...; do
...
done <"$tmpfile"
rm "$tmpfile"


Also related:



  • Why is my variable local in one 'while read' loop, but not in another seemingly similar loop?

An answer to the above linked question also suggests writing your program in such a way that all uses of $SOMEVAR occurs within the subshell at the end of the pipeline:



MULTILINE=$(cat "$SOMEFILE")
SOMEVAR="original value"

printf '%sn' "$MULTILINE" |
while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
printf 'this is a single line: %sn' "$SINGLELINE"
printf 'SOMEVAR is now: %sn' "$SOMEVAR"
done

printf 'Final SOMEVAR is: %sn' "$SOMEVAR"



Also possibly related:



  • Why is using a shell loop to process text considered bad practice?

Other questions that may be of interest:



  • Why is printf better than echo?

  • Are there naming conventions for variables in shell scripts?





share|improve this answer















You would read directly from the file without the pipeline. This avoids running the while loop in a subshell, which allows you to see the changed value of $SOMEVALUE after the loop.



SOMEVAR="original value"

while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
printf 'this is a single line: %sn' "$SINGLELINE"
printf 'SOMEVAR is now: %sn' "$SOMEVAR"
done <"$SOMEFILE"

printf 'Final SOMEVAR is: %sn' "$SOMEVAR"


If you insist on having your $MULTILINE variable, then write that to a file and read it from there:



tmpfile=$(mktemp)
printf '%sn' "$MULTILINE" >"$tmpfile"

while ...; do
...
done <"$tmpfile"
rm "$tmpfile"


Also related:



  • Why is my variable local in one 'while read' loop, but not in another seemingly similar loop?

An answer to the above linked question also suggests writing your program in such a way that all uses of $SOMEVAR occurs within the subshell at the end of the pipeline:



MULTILINE=$(cat "$SOMEFILE")
SOMEVAR="original value"

printf '%sn' "$MULTILINE" |
while IFS= read -r SINGLELINE
do
SOMEVAR="updated value"
printf 'this is a single line: %sn' "$SINGLELINE"
printf 'SOMEVAR is now: %sn' "$SOMEVAR"
done

printf 'Final SOMEVAR is: %sn' "$SOMEVAR"



Also possibly related:



  • Why is using a shell loop to process text considered bad practice?

Other questions that may be of interest:



  • Why is printf better than echo?

  • Are there naming conventions for variables in shell scripts?






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 31 at 11:35

























answered Mar 31 at 11:24









KusalanandaKusalananda

141k18264440




141k18264440












  • Indeed this works, but requires a file to be fed to the while-loop. My actual code is more complex, and requires a modified multiline string to be fed to the while-loop. Your solution to write this multiline string to a temporary file works, but is there a solution that does not require writing a temporary file?

    – Steiner
    Mar 31 at 11:28











  • @Steiner See update answer. There's not much else you could do without using features of specific shells.

    – Kusalananda
    Mar 31 at 11:33











  • Thank you that answers my question. The suggestion at the end and the links provided are very helpful too!

    – Steiner
    Mar 31 at 11:43











  • @Steiner ... except for using a here-document. Well, there's a thing I didn't think of :-)

    – Kusalananda
    Mar 31 at 18:42

















  • Indeed this works, but requires a file to be fed to the while-loop. My actual code is more complex, and requires a modified multiline string to be fed to the while-loop. Your solution to write this multiline string to a temporary file works, but is there a solution that does not require writing a temporary file?

    – Steiner
    Mar 31 at 11:28











  • @Steiner See update answer. There's not much else you could do without using features of specific shells.

    – Kusalananda
    Mar 31 at 11:33











  • Thank you that answers my question. The suggestion at the end and the links provided are very helpful too!

    – Steiner
    Mar 31 at 11:43











  • @Steiner ... except for using a here-document. Well, there's a thing I didn't think of :-)

    – Kusalananda
    Mar 31 at 18:42
















Indeed this works, but requires a file to be fed to the while-loop. My actual code is more complex, and requires a modified multiline string to be fed to the while-loop. Your solution to write this multiline string to a temporary file works, but is there a solution that does not require writing a temporary file?

– Steiner
Mar 31 at 11:28





Indeed this works, but requires a file to be fed to the while-loop. My actual code is more complex, and requires a modified multiline string to be fed to the while-loop. Your solution to write this multiline string to a temporary file works, but is there a solution that does not require writing a temporary file?

– Steiner
Mar 31 at 11:28













@Steiner See update answer. There's not much else you could do without using features of specific shells.

– Kusalananda
Mar 31 at 11:33





@Steiner See update answer. There's not much else you could do without using features of specific shells.

– Kusalananda
Mar 31 at 11:33













Thank you that answers my question. The suggestion at the end and the links provided are very helpful too!

– Steiner
Mar 31 at 11:43





Thank you that answers my question. The suggestion at the end and the links provided are very helpful too!

– Steiner
Mar 31 at 11:43













@Steiner ... except for using a here-document. Well, there's a thing I didn't think of :-)

– Kusalananda
Mar 31 at 18:42





@Steiner ... except for using a here-document. Well, there's a thing I didn't think of :-)

– Kusalananda
Mar 31 at 18:42











0














It works for me :



$ cat bin/test
#! /bin/sh
SOMEFILE=$1
MULTILINE="`cat $SOMEFILE`"
SOMEVAR="blah"

echo "$MULTILINE" | while IFS= read -r SINGLELINE
do
echo "this is a single line: $SINGLELINE"
echo "but accessing this var fails: $SOMEVAR"
done


and



$ bin/test bin/test
this is a single line: #! /bin/sh
but accessing this var fails: blah
this is a single line: SOMEFILE=$1
but accessing this var fails: blah
this is a single line: MULTILINE="`cat $SOMEFILE`"
but accessing this var fails: blah
this is a single line: SOMEVAR="blah"
but accessing this var fails: blah
this is a single line:
but accessing this var fails: blah
this is a single line: echo "$MULTILINE" | while IFS= read -r SINGLELINE
but accessing this var fails: blah
this is a single line: do
but accessing this var fails: blah
this is a single line: echo "this is a single line: $SINGLELINE"
but accessing this var fails: blah
this is a single line: echo "but accessing this var fails: $SOMEVAR"
but accessing this var fails: blah
this is a single line: done
but accessing this var fails: blah





share|improve this answer























  • My apologies. In trying to create a minimized sample of the actual issue, i made some errors. I updated the code sample now, and it should reflect the problem correctly now.

    – Steiner
    Mar 31 at 11:13















0














It works for me :



$ cat bin/test
#! /bin/sh
SOMEFILE=$1
MULTILINE="`cat $SOMEFILE`"
SOMEVAR="blah"

echo "$MULTILINE" | while IFS= read -r SINGLELINE
do
echo "this is a single line: $SINGLELINE"
echo "but accessing this var fails: $SOMEVAR"
done


and



$ bin/test bin/test
this is a single line: #! /bin/sh
but accessing this var fails: blah
this is a single line: SOMEFILE=$1
but accessing this var fails: blah
this is a single line: MULTILINE="`cat $SOMEFILE`"
but accessing this var fails: blah
this is a single line: SOMEVAR="blah"
but accessing this var fails: blah
this is a single line:
but accessing this var fails: blah
this is a single line: echo "$MULTILINE" | while IFS= read -r SINGLELINE
but accessing this var fails: blah
this is a single line: do
but accessing this var fails: blah
this is a single line: echo "this is a single line: $SINGLELINE"
but accessing this var fails: blah
this is a single line: echo "but accessing this var fails: $SOMEVAR"
but accessing this var fails: blah
this is a single line: done
but accessing this var fails: blah





share|improve this answer























  • My apologies. In trying to create a minimized sample of the actual issue, i made some errors. I updated the code sample now, and it should reflect the problem correctly now.

    – Steiner
    Mar 31 at 11:13













0












0








0







It works for me :



$ cat bin/test
#! /bin/sh
SOMEFILE=$1
MULTILINE="`cat $SOMEFILE`"
SOMEVAR="blah"

echo "$MULTILINE" | while IFS= read -r SINGLELINE
do
echo "this is a single line: $SINGLELINE"
echo "but accessing this var fails: $SOMEVAR"
done


and



$ bin/test bin/test
this is a single line: #! /bin/sh
but accessing this var fails: blah
this is a single line: SOMEFILE=$1
but accessing this var fails: blah
this is a single line: MULTILINE="`cat $SOMEFILE`"
but accessing this var fails: blah
this is a single line: SOMEVAR="blah"
but accessing this var fails: blah
this is a single line:
but accessing this var fails: blah
this is a single line: echo "$MULTILINE" | while IFS= read -r SINGLELINE
but accessing this var fails: blah
this is a single line: do
but accessing this var fails: blah
this is a single line: echo "this is a single line: $SINGLELINE"
but accessing this var fails: blah
this is a single line: echo "but accessing this var fails: $SOMEVAR"
but accessing this var fails: blah
this is a single line: done
but accessing this var fails: blah





share|improve this answer













It works for me :



$ cat bin/test
#! /bin/sh
SOMEFILE=$1
MULTILINE="`cat $SOMEFILE`"
SOMEVAR="blah"

echo "$MULTILINE" | while IFS= read -r SINGLELINE
do
echo "this is a single line: $SINGLELINE"
echo "but accessing this var fails: $SOMEVAR"
done


and



$ bin/test bin/test
this is a single line: #! /bin/sh
but accessing this var fails: blah
this is a single line: SOMEFILE=$1
but accessing this var fails: blah
this is a single line: MULTILINE="`cat $SOMEFILE`"
but accessing this var fails: blah
this is a single line: SOMEVAR="blah"
but accessing this var fails: blah
this is a single line:
but accessing this var fails: blah
this is a single line: echo "$MULTILINE" | while IFS= read -r SINGLELINE
but accessing this var fails: blah
this is a single line: do
but accessing this var fails: blah
this is a single line: echo "this is a single line: $SINGLELINE"
but accessing this var fails: blah
this is a single line: echo "but accessing this var fails: $SOMEVAR"
but accessing this var fails: blah
this is a single line: done
but accessing this var fails: blah






share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 31 at 11:11









RedocTsujRedocTsuj

1




1












  • My apologies. In trying to create a minimized sample of the actual issue, i made some errors. I updated the code sample now, and it should reflect the problem correctly now.

    – Steiner
    Mar 31 at 11:13

















  • My apologies. In trying to create a minimized sample of the actual issue, i made some errors. I updated the code sample now, and it should reflect the problem correctly now.

    – Steiner
    Mar 31 at 11:13
















My apologies. In trying to create a minimized sample of the actual issue, i made some errors. I updated the code sample now, and it should reflect the problem correctly now.

– Steiner
Mar 31 at 11:13





My apologies. In trying to create a minimized sample of the actual issue, i made some errors. I updated the code sample now, and it should reflect the problem correctly now.

– Steiner
Mar 31 at 11:13

















draft saved

draft discarded
















































Thanks for contributing an answer to Unix & Linux Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f509714%2fiterate-through-multiline-string-line-by-line%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Triangular numbers and gcdProving sum of a set is $0 pmod n$ if $n$ is odd, or $fracn2 pmod n$ if $n$ is even?Is greatest common divisor of two numbers really their smallest linear combination?GCD, LCM RelationshipProve a set of nonnegative integers with greatest common divisor 1 and closed under addition has all but finite many nonnegative integers.all pairs of a and b in an equation containing gcdTriangular Numbers Modulo $k$ - Hit All Values?Understanding the Existence and Uniqueness of the GCDGCD and LCM with logical symbolsThe greatest common divisor of two positive integers less than 100 is equal to 3. Their least common multiple is twelve times one of the integers.Suppose that for all integers $x$, $x|a$ and $x|b$ if and only if $x|c$. Then $c = gcd(a,b)$Which is the gcd of 2 numbers which are multiplied and the result is 600000?

Ingelân Ynhâld Etymology | Geografy | Skiednis | Polityk en bestjoer | Ekonomy | Demografy | Kultuer | Klimaat | Sjoch ek | Keppelings om utens | Boarnen, noaten en referinsjes Navigaasjemenuwww.gov.ukOffisjele webside fan it regear fan it Feriene KeninkrykOffisjele webside fan it Britske FerkearsburoNederlânsktalige ynformaasje fan it Britske FerkearsburoOffisjele webside fan English Heritage, de organisaasje dy't him ynset foar it behâld fan it Ingelske kultuergoedYnwennertallen fan alle Britske stêden út 'e folkstelling fan 2011Notes en References, op dizze sideEngland

Հադիս Բովանդակություն Անվանում և նշանակություն | Դասակարգում | Աղբյուրներ | Նավարկման ցանկ