You may not need to use external tools like sort
, whose options and usage may vary depending on your operating system. Bash has an internal random number generator accessible through the $RANDOM
variable. It's common practice to seed the generator by setting the variable, like so:
RANDOM=$$
or
RANDOM=$(date '+%s')
etc. But of course, you can also use a predictable seed in order to get predictable not-so-random results:
$ RANDOM=12345; echo $RANDOM
28207
$ RANDOM=12345; echo $RANDOM
28207
To reorder the lines of the mapped file randomly, you can read the file into an array using mapfile:
$ mapfile -t a < source.txt
Then simply rewrite the array indices:
$ for i in ${!a[@]}; do a[$((RANDOM+${#a[@]}))]="${a[$i]}"; unset a[$i]; done
When reading a non-associative array, bash naturally orders elements in ascending order of index value.
Note that the new index for each line has the number of array elements added to it to avoid collisions within that range. This solution is still fallible -- there's no guarantee that $RANDOM
will produce unique numbers. You can mitigate that risk with extra code that checks for prior use of each index, or reduce the risk with bit-shifting:
... a[$(( (RANDOM<<15)+RANDOM+${#a[@]} ))]= ...
This makes your index values into a 30-bit unsigned int instead of a 15 bit unsigned int.