Getting the size of a directory using bash

Sometimes as a system admin you would like to automate tasks based on how large a particular directory/folder is on a computer, or for a homework assignment in school. The very simple script below takes one argument, a path to the folder you would like to know the size of. It then will calculate the total size on the disk this folder and it contents take up and return in MB the folder size. It is a very simple script so I could see this being helpful to people new to bash scripting.


# Author: Joseph J. Viscomi   E-Mail: jviscomi [at] brehm [dot] org || jviscomi [at] brehm [dot] org
# Date:   3/23/2011
# Arguments: Absolute path to a folder.
# Description: Prints the size of the folder in MB to standard out.
# Erros: Should handle all errors gracfully by returning -1.

# Checks to see that you gave it a directory and that it
# exists!
if [ $# = 1 ] && [ -d $1 ]
  du -sm $1 | cut -f 1
  # Echo -1 since NO folder can take up -1 M
  echo -1


Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Performance Optimization WordPress Plugins by W3 EDGE