Bash: How to Find the Largest File in a Directory


Often you may want to find the largest file in a specific directory in Bash.

You can use the following syntax to do so:

du -h * | sort -rh | head -n 1

This particular example will display the name of the largest file in the current directory along with the size of the file in a human readable format.

Here is what the various commands do:

  • du -a -h: Obtain disk usage ( du ) information for files in current directory in human readable format ( -h *)
  • -sort -rh: Sort results in reverse order ( -r ) using human readable format ( -h )
  • head -n 1: Only display the 1 largest file

Note that you can replace the 1 with n to instead display the n largest files in the directory.

The following example shows how to use this syntax in practice.

Example: How to Find the Largest File in a Directory in Bash

Suppose that we would like to find the largest file in our current directory.

We can use the following command to first view all files along with their sizes:

du -h *

The following screenshot shows how to use this syntax in practice:

We can then use the following syntax to only display the largest file:

du -h * | sort -rh | head -n 1

The following screenshot shows how to use this syntax in practice:

Bash find largest file in directory

We can see that this returns the file named athletes.csv, which has a file size of 8.0k.

Note that we can replace the 1 with a different number to instead return the n largest files in the directory.

For example, we can use the following syntax to return the 3 largest files in the directory:

du -h * | sort -rh | head -n 3

The following screenshot shows how to use this syntax in practice:

Bash find N largest files in directory

This returns the 3 largest files in the directory, sorted from largest to smallest based on size.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to List All Files in Folder by Size
Bash: How to Delete All Files in Directory
Bash: How to Delete All Empty Lines in File

Leave a Reply