Iterating over each line of ls -l output

linux, shell

Solution

Set IFS to newline, like this:

IFS='
'
for x in `ls -l $1`; do echo $x; done

Put a sub-shell around it if you don't want to set IFS permanently:

(IFS='
'
for x in `ls -l $1`; do echo $x; done)

Or use while | read instead:

ls -l $1 | while read x; do echo $x; done

One more option, which runs the while/read at the same shell level:

while read x; do echo $x; done << EOF
$(ls -l $1)
EOF

Problem

I want to iterate over each line in the output of: `ls -l /some/dir/*` Right now I'm trying: `for x in $(ls -l $1); do echo $x; done` However, this iterates over each element in the line separately, so I get: ``` -r--r----- 1 ivanevf eng 1074 Apr 22 13:07 File1 -r--r----- 1 ivanevf eng 1074 Apr 22 13:17 File2 ``` But I want to iterate over each line as a whole, though. How do I do that?

Original source