How to store bash shuf to string

In this short guide, I'll show you how to store the output of bash command shuf to string or variable.

bash shuf to string

To store the output of the shuf command into a variable, use the following syntax for file input:

shuff_output=$(shuf input_file)

This will store the shuffled input of input_file in the variable shuff_output.

Another shuf example for random number generation:

id_num=$(shuf -i 0-99 -n 1);
id_str="$id_num";

First line generates a random number in range 0-99. The second line converts the number to string.

Next sections explain how the code above works.

store command output to variable

In bash, to store the output of a command into a string or variable use the following syntax:

variable_name=$(command)

shuf example

Bash shuf command can be used to generate numbers in a range of values. For example generating 8 digit random numbers from 0 to 999:

shuf -i 0-999 -n 1

where:

  • -i, --input-range
    • 0-999 - the range for the random numbers
  • -n, --head-count=COUNT
    • 1 - number of returned elements

Generate random number in bash from 1 to 100:

shuf -i 1-100 -n 1