Bash: Iterating over lines in a variable
Problem
How does one properly iterate over lines in bash either in a variable, or from the output of a command? Simply setting the IFS variable to a new line works for the output of a command but not when processing a variable that contains new lines. For example This gives the output: As you can see, echoing the variable or iterating over the command prints each of the lines one by one correctly. However, the first for loop prints all the items on a single line. Any ideas?
Error Output
#!/bin/bash
list="One\ntwo\nthree\nfour"
#Print the list with echo
echo -e "echo: \n$list"
#Set the field separator to new line
IFS=$'\n'
#Try to iterate over each line
echo "For loop:"
for item in $list
do
echo "Item: $item"
done
#Output the variable to a file
echo -e $list > list.txt…Unverified for your environment
Select your OS to check compatibility.
1 Fix
Fix for: Bash: Iterating over lines in a variable
With bash, if you want to embed newlines in a string, enclose the string with : And if you have such a string already in a variable, you can read it line-by-line with: @wheeler makes a good point about adding a trailing newline. Suppose the variable ends with a newline Then the while loop outputs To get around that, use a redirection from a process substitution instead of a here-string But now this "fails" for strings without a trailing newline The documentation says The exit status is zero, un…
Awaiting Verification
Be the first to verify this fix
Sign in to verify this fix