Calendar
Bookmarks
Categories
Statistics
Last entry: 2013-05-20 12:21
275 entries written
90 comments have been made
Sunday, April 15. 2012
Bash - looping or capturing a multiple line command output
I tried to loop a command which returns a multi-line result in a bash script. The problem was that the quoted command returned ONE line instead of each line separately. So I ended with one line consisted of multi-line result while I was expecting that the quotes would preserve the spacing. Without quotes I got each "word" in a new line while I was expecting everything in one line (without quotes should replace multiple blanks, tabs and newlines with a single space). Here is the "faulty" script:
#for line in `ls -l` #for line in $(ls -l) for line in "$(ls -l)" do echo $line"XXX" done
Not quite sure if this is due to OS X (or BSD) environment but I got around it by piping the command to the while loop:
(ls -l) | while read line do echo $line"xxx" done
or
while read line; do echo $line"xxx" done < <(ls -l)

