Tcl
dirsize.tcl


return to misc index



This Tcl script provides a procedure that calculates the total size in bytes of a (parent) directory including all its (child) sub-directories and files. The procedure uses recursion to examine the directory structure of the target directory.

The script examines each item in a directory. If the item is a sub-directory it calls itself ie. it recurses. Each time the procedure is called it is passed the full path of the directory it is to "examine" as well as a reference to a global variable that keeps a count of the total number of bytes of each directory and file contained in the parent directory.

If the script is run with the comment on line 8 removed you will see a listing of the directories/files and their sizes displayed in the terminal/command window.


Listing 1


proc dirsize { dir totalsize } {
    # enable a local variable to reference
    # the global "totalsize" variable
    upvar $totalsize bytes
    
    set contents [glob -directory $dir *]
    foreach item $contents {
       #puts "[format "%32s %f" $item [file size $item]]"
       set bytes [expr $bytes + [file size $item]]
    
       if { [file isdirectory $item] } {
          # recurse ie. call ourself
          dirsize $item bytes
       } elseif { [file isfile $item]} {
          # nothing to do
          }
       }
    }


The input parameters are:

dirsize
    dir          the full path of the target directory
    totalsize    a variable that keeps a running
                 total of byte count ie. size

Example:
A directory called "CV" contains 10 files of various 
types. The directory is located at 
    "/Users/Documents/CV" 
To find the size of this directory and its contents the
dirsize procedure might be used by another Tcl script 
as follows.
    
    source /Users/Documents/TCL/listfiles.tcl
    # print the directory size to the console
    set total 0.0
    dirsize "/Users/Documents/CV" total
    puts "Total size of the CV directory is [format "%1.3f" [expr $total / 1000000]] Mb"

The output might look like this,
    Total size of the CV directory is 5.413 Mb
    
Note the use of the source command to "point" the 
Tcl interpreter at the directory containing
the dirsize.tcl script.
  
Refer to dirlist for an example of specifying paths for Windows.



© 2002- Malcolm Kesson. All rights reserved.