Nono.MA

Randomize a list of strings in Bash with shuf

FEBRUARY 13, 2023

Here's how to randomize a list of strings in bash.

On macOS, you can use Terminal or iTerm2.

The shuf command shuffles a list that is "piped" to it.

Shuffling the contents of a directory

An easy way to do that is to list a directory's contents with ls and then shuffle them.

ls ~/Desktop | shuf

Shuffling a list of strings

The easiest way to shuffle a set of strings is to define an array in bash and shuffle it with shuf.

WORDS=('Milk' 'Bread' 'Eggs'); shuf -e ${WORDS[@]}

You can use pbcopy to copy the shuffled list to your clipboard.

WORDS=('Milk' 'Bread' 'Eggs' ); shuf -e ${WORDS[@]} | pbcopy

Shuffling lines from a text file

Another way to randomize a list of strings from bash is to create a text file, in this case named words.txt, with a string value per line.

Bread
Milk
Chicken
Turkey
Eggs

You can create this file manually or from the command-line with the following command.

echo "Bread\nMilk\nChicken\nTurkey\nEggs" > words.txt

Then, we cat the contents of words.txt and shuffle order of the lines with shuf.

cat words.txt | shuf
# Eggs
# Milk
# Chicken
# Turkey
# Bread

Again, you can save the result to the clipboard with pbcopy.

cat words.txt | shuf | pbcopy

If you found this useful, let me know!

BlogCodeBashTil