Shell script for daily disk usage report

disk-space-utilizationscripting

I am doing backups on my local drives. The drives are mounted in /media folder.
Now I want to run a cron job daily which will tell me, in a table format, how much disk is used by certain folders and how much free space is left on the drive.

It would be good if I can insert that info into a database and I can see that info via a webpage on locahost.

I am using Ubuntu 10.04.

Best Answer

This one-liner will list the top-level directories from the directory it is executed in, and print their sizes sorted in MB. You can tweak it for your tastes.

for d in $(find . -maxdepth 1 -type d); do du -sm $d; done | sort -nk 1

Simple tweaks,

  1. find /dir/path -- will do this for a specified directory
  2. du can be used in other forms, this one is doing a summary in MB
  3. If your directories have the space characters, you can precede with,
    (as further cleaned-up by Dennis; thanks for that tip)
    IFS=$'\n';
    I am somehow used to exact filters rather than globbing; Dennis has more ideas
  4. You can use sort -nrk 1 to sort the output in descending order of size
  5. I missed adding -mindepth 1 there,
    When you add that, it will skip showing the base-directory (/dir/path etc) size in the results

Some other answer here will probably give you a good handle on storing this into databases and displaying on web-pages. I would have just converted it to CSV files and listed summaries with a file path in the browser (but, that may not be too optimal for storage and view with lots of data over time).

[meta, editing query: the fourth item shows up as 4 in the preview when I edit this answer,
but says 1 in the real-view. Anyone know what I am missing in this markdown?;
This got fixed when I removed the newlines in point-3,
you'll need to look at the earlier revision to see what I mean here...]


Update with basics (based on your comment):

  1. Look at using the terminal for command-line processing with Ubuntu
  2. Once you have the terminal started,
    Change to a directory of interest (try some sample directory),
    (maybe your firefox profile for example -- cd ./mozilla)
    and, don't try too many things in that directory, you could break your browser.
  3. Now copy the first for-loop line as-is from above and paste it on the command prompt in that terminal
  4. press the Enter key
  5. look at the output
  6. Another reference to get more on how to use the command-line for 'scripting',
    Bash Shell Tutorials at Superuser

Tell us which level of detail you want from there.

Related Topic