Bash – Get Exact Size of Files from Find Output

bashbusyboxcommand linedisk-usagefind

My shell engine is either Busybox 1.31.0 or bash 3.2

I need to get the size of the files retrieved from find command.

I've been trying to find only files, which have been modified more than 60 days ago and at the same time get the size of all those files SUMARIZED preferably in a one-liner in MB notation. Here's what I've tried.

find -type f -mtime +60 -print0 | xargs -0 du -smc

and

find -type f -mtime +60 -exec du -smc {} \;

The former retrieves line-by-line all files older than 60 days (no problem at all until here) but it weirdly calculates the size several times between all those lines and at the final line I get a "total" size that does not correspond to the actual total size of the output. Here's what it looks like.

.....
.....
0       ./FOLDER 2018/Copy #183 of ~$DATABASE OTHERS - NOV.18N.xlsx
42      ./FOLDER 2018/F9C8A618.tmp
0       ./FOLDER 2018/Copy #166 of ~$DATABASE PORTFOLIO NOV.18.xlsx
3275    total
10      ./FOLDER 2018/CFDC6981.tmp
2       ./FOLDER 2018/D5AAF4EB.tmp
0       ./LIFE INSURANCE/Copy #15 of ~$Copy of LIFE INSURANCE CLIENTS.xlsx
12      total

The latter's output calculate the size of every coinciding file line-by-line with no total.

What I'm expecting is:

    0       ./FOLDER 2018/Copy #183 of ~$DATABASE OTHERS - NOV.18N.xlsx
    42      ./FOLDER 2018/F9C8A618.tmp
    0       ./FOLDER 2018/Copy #166 of ~$DATABASE PORTFOLIO NOV.18.xlsx
    10      ./FOLDER 2018/CFDC6981.tmp
    2       ./FOLDER 2018/D5AAF4EB.tmp
    0       ./LIFE INSURANCE/Copy #15 of ~$Copy of LIFE INSURANCE CLIENTS.xlsx
    54      total

Or simply just the real size result without all the lines

54      total

Any help would be well received.

Best Answer

Try pipe the output of find to du and specify the --files0-from - flag:

find -type f -mtime +60 -print0 | du -shc --files0-from -

This should give you a grand total at the end

To get just the total, pipe that output to tail -n1:

find -type f -mtime +60 -print0 | du -shc --files0-from - | tail -n1

I should mention that I actually just tested this with gnu linux, not busybox. Looking at the busybox page, it does not look like du supports the --files0-from option.

You can change the above command to this to have it work on busybox:

find -type f -mtime +60 -print0 | xargs -0 du -ch | tail -n1

The above also works with files with spaces and newlines in their names, but may not work well if there are too many files found by find command. See the below comment. If you feel that there may be too many files, you can try the other answer on this page.

Related Question