How to Randomize Lines of Text Using the shuf Command in Linux

When you are building a complex automated script that requires unpredictable variables—such as pulling a random password from a master list or assigning a random port number for a server connection—you cannot rely on static data. If a script always selects the first line of a file, the system becomes dangerously predictable. To force the Linux kernel to execute a highly complex mathematical permutation and violently randomize the internal structure of any text file, you must use the shuf command.

Executing a Full Random Permutation

The shuf (Shuffle) command is a cryptographic-level randomization engine. It loads an entire text file into memory, completely shatters the existing line structure, and mathematically reassembles the file in a completely chaotic, random order.

Assume you have a file named servers.txt containing a list of 100 different server IP addresses in strict numerical order.

shuf servers.txt

The exact millisecond you press Enter, the terminal output is instantly scrambled. The engine outputs all 100 lines, but the sequence is completely destroyed, creating a mathematically perfect random distribution.

Extracting a Single Random Variable

While shuffling an entire file is useful, the true power of the shuf command is unleashed when you need to extract exactly one random data point for an automated bash script.

By injecting the -n (number) flag, you can mathematically constrain the output engine.

shuf -n 1 servers.txt

The system executes the massive random permutation in the background, but it only outputs exactly one randomly selected IP address to the screen. If you run the command again, it will output a completely different IP address. This is highly efficient for load-balancing scripts that need to select a random server from a master pool.

Generating Random Number Sequences

You do not actually need a physical text file to use the shuf engine. You can force it to generate and scramble its own raw numerical data using the -i (input range) flag.

If you need to instantly generate 5 completely random port numbers between 1000 and 9999, type:

shuf -i 1000-9999 -n 5

The engine instantly calculates the massive 9,000-number block, executes a chaotic shuffle, and outputs exactly 5 random, perfectly bounded integers directly to your terminal screen.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.