Bash: How to Select Random Files from Directory


Often you may want to select one or more random files from a directory in Bash.

The easiest way to do so is by using the following syntax:

ls | shuf -n 4

This particular example selects 4 files randomly from the current directory.

Here is what the various commands do:

  • ls: List all files in current directory
  • shuf: “Shuffle” the files in the directory randomly
  • -n: Specifies the number of files to return

To select a different number of files, simply change the 4 to a different number.

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

Example: How to Select Random Files from Directory in Bash

Suppose that we would like to randomly select 4 files from our current directory.

Before we do so, we can first use the ls command to view all files in the current directory:

From the output we can see that the current directory contains the following files:

  • coaches.txt
  • employees.csv
  • interns.csv
  • owners.txt
  • players.txt
  • teams1.txt
  • teams2.txt

Suppose that we would like to randomly select four of these files from the directory.

We can use the following syntax to do so:

ls | shuf -n 4

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

Bash select random files from directory

Notice that this returns four random files from the directory:

  • owners.txt
  • interns.csv
  • players.txt
  • teams1.txt

Note that each time we run this code we may get a different set of four files from the directory.

Note: Feel free to change the number provided after the -n operator to instead randomly select a different number of files from the directory.

Related Tutorials

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

Bash: How to Generate Random Number in Range
Bash: How to Select Random Lines from a File
Bash: How to List All Files Matching a Specific Pattern

Leave a Reply