shuf

shuf shuffles: it outputs its input lines in a random order. Every possible ordering is equally likely.

shuf [options] [file]
shuf -e [options] arg...
shuf -i lo-hi [options]
$ shuf playlist.txt

shuf is the opposite of sort — instead of imposing an order, it removes one. With no file, it reads standard input.

Where the lines come from #

shuf has three ways of getting its input, one per usage form:

OptionInput is…
(a file, or stdin)the lines of the file.
-e, --echothe command-line arguments, each treated as one line.
-i, --input-range=LO-HIthe integers from LO to HI, each treated as one line.
$ shuf -e red green blue          # shuffle three given words
$ shuf -i 1-100                   # the numbers 1..100 in random order

Shaping the output #

OptionEffect
-n, --head-count=COUNTOutput at most COUNT lines — a random sample rather than the whole shuffle.
-r, --repeatAllow lines to be repeated, so output can be longer than the input. Pair with -n to set how many.
-o, --output=FILEWrite to FILE instead of standard output.
-z, --zero-terminatedTreat the NUL character as the line delimiter.

shuf -n 1 is a common idiom — pick one random line.

Reproducible shuffles #

A shuffle is random by default. To get the same shuffle every time — for a repeatable test, say — fix the randomness:

OptionEffect
--random-seed=STRINGSeed the shuffle with STRING. The same seed gives the same shuffle.
--random-source=FILETake the random bytes from FILE. The same file gives the same shuffle. Cannot be combined with --random-seed.

Exit status #

CodeMeaning
0Success.
1A failure — the input could not be read, or -r was used with no lines to repeat.

Edit this page