Search code examples
bashloopsfilesize

Access file characteristics / attributes in bash loop


I'm learning more about bash scripting. When looping through files in a directory, I want to be able to echo out more than just the filename. How do I access associated file data?

This example code I have used to list all files in a folder.

for file in .* *; do echo "$file"; done

What do I add need to do to access the $file size or date? I noticed it's not as easy as just $file.size and $file.date.


Solution

  • Although you call them "file", what you get are just strings with the file names. In each iteration of the for loop, you can use $file with other commands ( for example "stat" or "ls -l"), to extract information about the files, and then you will have to parse its output (with "awk" or "sed").

    So the solution will be:

    for file in .* *; do COMMAND_TO_GET_INFO "$file" | COMMAND_TO_PARSE_OUTPUT ; done
    

    where COMMAND_TO_GET_INFO and COMMAND_TO_PARSE_OUTPUT could be different commands according to what you need.