Disk Usage

“What happened to all my disk space!”

It can be amazing how quickly all your disk’s capacity gets filled up with random files and forgotten downloads. Here are a few commands to point you towards some of the culprits clogging up your file system.

This command will list the largest 10 objects in the current directory.

sudo du -a . | sort -n -r | head -n 10

Here’s the breakdown of the command: du is a utility on mac and linux that can list disk usage of directories and files. The -a option specifies du to list all (both files and directories). The period stands for the current directory (so you could change this to any directory you want to examine that folder’s disk usage). The sudo command executes the following command (du) as the root user so that you will be able to read all the files and folders on the system.

The pipe character ( | ) captures the output of the command to its left and makes it the input to the command on the right. So the output of du gets piped into sort, which sorts lists of things. The -n and -r flags direct it to sort the list like they are numbers (since we are giving the file sizes, they are numbers) and to sort in reverse order. We then pipe the output of the sort into the head command. head will display only the first few lines of input. We specify how many lines to read by passing the -n flag followed by the number of lines to read: 10, because we want to see only the 10 largest files.

Welcome to CLI Magic!

The command line is a seriously powerful place, but it can be a bit like arcane magic trying to divine the right incantation of flags and commands.

This will be a series of short posts that give one or two commands that do something really cool or powerful in a condensed form, with a short explanation of what they do. They might be useful or just fun. The commands here will be primarily for Bash on Mac/Linux but can usually be adapted for most *nix environments.

Let’s begin with a command I used the other day. This is useful if you want to view a file kept on a remote computer using your favorite text editor on your mac (without depending on any X window nonsense)

ssh user@server.name "cat /absolute/path/to/file" | open -fa "/Applications/Example.app"

For example I opened a wordpress theme php file with sublime text to debug the website

ssh root@ourserverat.eclarian.com "cat /example/wp-content/themes/MyTheme/template-home.php" | open -fa "/Applications/Sublime Text.app"

(And no that is not the real name of our servers)