Anish Sethi Anish Sethi - 1 year ago 62
Bash Question

Write a shell script to calculate the size of each project in a directory?

I want to write a shell script to calculate how much space each project folder is occupying on my server, suppose i have a Home folder in which numerous project folders are there, rather than writing

du -sh "project name"
every time want it to calculate it correspondingly in one file like :

ABC 40 Gb

Answer Source

A simple find command would suffice:-

find /your/path -maxdepth 1 -mindepth 1 -type d -exec du -sh "{}" \;

Refer this man find page to see how the options are used.

To summarize the options:-

  • -type d & -maxdepth 1 looks for only folders from the path mentioned which in your case /your/path at one folder level
  • Thanks to frist's suggestion below adding the -mindepth 1 flag lets you avoid re-calculating the size of all the folders combined.
  • -exec runs the du -sh command on each of the directory returned by find. Each of the directory is identified by {}, and double-quotes are added to preserve the original directory name
  • \; runs the command once for each directory.

Sample output:-

4.0K ./myfolder
24K  ./destfolder
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download