0

I have the following code from a script below that's supposed to capture the output of ls -l on your current directory and discard the first line, where total is written. Then output to the terminal for every file the permission, owner and file name and at the end the total number of lines. The problem is if in the directory there is a file containing white space in the name it's not listed correctly. Why not?

list=`ls -l`

IFS_old=$IFS
IFS=$'\n'
i=0
for row in $list
do
    if (( $i == 0 )); then 
        ((i++))
    else
        IFS=$' '
        j=0
        for attrib in $row
        do
            ((j+=1))
            if (( $j == 1 )) || (( $j == 3 )) || (( $j == 5 )) || (( $j == 9 )); then 
                printf "%s " $attrib
            fi
        done
        printf "\n"
        IFS=$'\n'
        ((i++))
    fi
done
printf "%s%s\n" "Total number of files : " $((i-1)) 
IFS=$IFS_old
exit 0
2

Trying to parse the output of ls is ill-advised, even when using an implementation that supports options for unambiguous output, such as -b or -Q in the GNU version.

Instead, you should use a shell glob to process files one at a time; in Bash, we can use an array for this:

#!/bin/bash

files=(*)

for i in "${files[@]}"
do
    stat --format '%A %U %n' -- "$i"
done

printf "Total number of files: %d\n" ${#files[@]}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.