How do I get the size of a directory on the command line?

  • I tried to obtain the size of a directory (containing directories and sub directories) by using the ls command with option l. It seems to work for files (ls -l file name), but if I try to get the size of a directory (for instance, ls -l /home), I get only 4096 bytes, although altogether it is much bigger.

    1) Strictly speaking, you can't. Linux has directories, not folders. 2) There's a difference between the size of a directory (which is a special file holding inodes that point to other files), and the size of the contents of that directory. As others have pointed out, the du command provides the latter, which is what it appears you want.

    as you seem to be new, I'll just point out the helpful `-h` option you can add to the `-l` option (i.e. `ls -lh`) to get the sizes of files to be printed out in human-friendly notation like 1.1M instead of 1130301. The "h" in the `du -hs` command that @sam gave as the answer for your question about directories also means "human-readable", and it also appears in `df -h` which shows the human readable amounts of used and free space on disk.

  • sam

    sam Correct answer

    6 years ago

    du -sh file_path

    Explanation

    • du (disc usage) command estimates file_path space usage
    • The options -sh are (from man du):

        -s, --summarize
               display only a total for each argument
      
        -h, --human-readable
               print sizes in human readable format (e.g., 1K 234M 2G)
      

      To check more than one directory and see the total, use du -sch:

        -c, --total
               produce a grand total
      

    It works very nice with `find` e.g. to count the amount of space in specific subdirectories in current path: `$ find . -type d -name "node_modules" -prune -exec du -sh {} \;`

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM