How To Shuffle Text and Numbers In Linux Using `shuf`

How to use Linux shuf command in Linux

Your Linux system comes pre-loaded with many helpful command line utilities. Some of these are commonly used and mentioned, like cat, grep, or diff. But there are many more utilities hidden in your system that might be of use to you. A good working knowledge of command line utilities can help you write small, efficient scripts, and give you a better overall sense of what you have available to you in your system for completing your tasks.

What are the use cases for shuffling text? With an obscure tool like shuf, an immediate use case is not obvious. But imagine you have a list, or several lines of text in a file, and you want to randomly sort them. Let’s say you have a list of server maintenance tasks, and you can’t decide which one to work on first. Let shuf shuffle them for you.

Shuffle Text From Standard Input

The shuf command will shuffle what you give it. Using the -e option, it will treat each operand as a separate input line:

$ shuf -e one two three
two
three
one

Notice how the random output sorted “one two three” into “two three one.”

Shuffle Lines of Text From File

But in many cases, you might not be shuffling data from standard input but instead feeding data from a file. For example, let’s say we have file called input.txt with the following lines of text:

First line
Second line
Third line

We can use shuf to shuffle each of these lines and provide us with a result:

$ shuf input.txt 
Third line
Second line
First line

Random Number Generation

With shuf, you can also easily simulate a dice roll or random number generation using numbers as input. The following command will simulate five rolls of a single die:

shuf -r -n 5 -i 1-6

The -r option allows a number to be repeated. The -n limits the amount of rolls to produce 5 lines of output, and -i indicates the range of input (in this case, 6).

If you don’t need cPanel, don't pay for it. Only pay for what you need with our scalable Cloud VPS Hosting.

check markCentOS, Debian, or Ubuntu check markNo Bloatware check markSSH and Root Access

CM
Christopher Maiorana Content Writer II

Christopher Maiorana joined the InMotion community team in 2015 and regularly dispenses tips and tricks in the Support Center, Community Q&A, and the InMotion Hosting Blog.

More Articles by Christopher

Was this article helpful? Join the conversation!