0

The while loop in my script is taking input from the variable, which has multiple lines, and processing the variable as one line. How can I get my while loop to process the variable line by line.

I'm looking for an alternative for how I can assign the variable "input", like I do here input=$(tail -n +2 $1), or an alternative to how I pass that variable into the while loop, like I do here done <<< $(echo $input)

Script

input=$(tail -n +2 $1)

echo "input: $input :input"

while IFS='' read -r line || [[ -n "$line" ]]; do
        echo "output: $line :output"
done <<< $(echo "$input")

Input File ( $1 )

header
test
test2
test3
test4

Output

input: test
test2
test3
test4 :input
output: test test2 test3 test4 :output

Desired Output

input: test
test2
test3
test4 :input
output: test :output
output: test2 :output
output: test3 :output
output: test4 :output

Update:

I executed these commands one after each other, so I don't know whats different on your end that my $(echo "$input") command isn't passing in the variable line by line

machine:folder user$ cat temp
#!/bin/BASH
input=$(tail -n +2 $1)

echo "input: $input :input"

while IFS='' read -r line || [[ -n "$line" ]]; do
    echo "output: $line :output"
done <<< $(echo "$input")
machine:folder user$ cat test
header
test
test2
test3
test4
machine:folder user$ ./temp test 
input: test
test2
test3
test4 :input
output: test test2 test3 test4 :output
machine:folder user$ BASH --version
GNU bash, version 4.4.12(1)-release (x86_64-apple-darwin16.5.0)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Sam
  • 1,765
  • 11
  • 82
  • 176
  • 1
    You use `echo $input` and find that your multiline variable is all on one line. Just quote it, as in `<<< $(echo "$input")`. You can also skip the unnecessary `echo` and just use `<<< "$input"` directly (both suggested by [shellcheck](http://shellcheck.net)). Or you can skip the variable entirely with `tail -n +2 $1 | while IFS='' read ...` – that other guy May 05 '17 at 17:35
  • Thank-you, it actually doesn't if I just add quotes though just so you know, but removing the echo as well as adding quotes to input fixes it for me; do you know why that is? – Sam May 05 '17 at 17:37
  • Running your updated example with the quotes gives your desired output in Bash 4.4.11. Can you copy your example from your post into a fresh file and double-check? – that other guy May 05 '17 at 17:41

0 Answers0