Chris Daly
Chris Daly

Reputation: 17

How to create a FOR loop in BASH that lists files in a certain format

I want to print all the files in my chosen directory. I want to format the files to be displayed under the column headers. But when I'm trying to run the below code I'm getting errors in the console.

list_files()
{   
    FILES=/home/student/.junkdir/
    echo "Listing files in Junk Directory"
    format="%8s%10s%10s   $-s\n"
    printf "$format" "Filename" "Size(Bytes)" "Type"
    printf "$format" "--------" "-----------" "----"
    for listed_file in $FILES; do
        file_name=$(du $listed_file | awk '{print $2}')
        file_size=$(du $listed_file | awk '{print $1}')
        file_type=$(file $listed_file | cut -d ' ' -f2-)
        printf "$format" $file_name $file_size $file_type
    done
}

This is the output

Listing files in Junk Directory
FilenameSize(Bytes)      Type   hBs
-------------------      ----   hBs
du: cannot access ‘/home/student/.junkdir/*’: No such file or directory
du: cannot access ‘/home/student/.junkdir/*’: No such file or directory
ERROR:    cannot      open   hBs
`/home/student/.junkdir/*'       (No      such   hBs
file        ordirectory)   hBs

Upvotes: 1

Views: 43

Answers (1)

glenn jackman
glenn jackman

Reputation: 247022

Use the stat command to get the data, and column to make the output pretty.

stat -c $'%n\t%s\t%F' * | column -ts $'\t'

In a function

list_files() {   
    local dir=/home/student/.junkdir/
    echo "Listing files in Junk Directory"
    {
        printf "%s\t%s\t%s\n" "Filename" "Size(Bytes)" "Type"
        stat -c $'%n\t%s\t%F' "$dir"/*
    } | column -t -s $'\t'
}

Upvotes: 1

Related Questions