Skip to content

Instantly share code, notes, and snippets.

@mschmitt
Created March 22, 2022 19:26
Show Gist options
  • Save mschmitt/fe4aa36602e0f1be6f2c55e81f983adf to your computer and use it in GitHub Desktop.
Save mschmitt/fe4aa36602e0f1be6f2c55e81f983adf to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
set -o errexit
# A native bash function to mimic the behaviour of shuf(1).
#
# - From the failed experiments department.
# - Unusably slow on long files with thousands of lines.
#
# "Arrays are sparse doubly-linked lists."
# https://git.savannah.gnu.org/cgit/bash.git/tree/array.c
function bashuf() {
if [[ ! -v SRANDOM ]]
then
echo "This bash function requires SRANDOM support. (Bash 5.1)"
exit 1
fi
mapfile -t lines
for (( todo=${#lines[@]}; todo > 0; todo-- ))
do
rand=$(( SRANDOM % todo ))
printf "%s\n" "${lines[${rand}]}"
# Unless rand gave us the last of the remaining lines,
# swap the last line to where we just read the
# random line from:
if [[ ${rand} -ne ${todo} ]]
then
lines[${rand}]="${lines[$((todo-1))]}"
fi
done
}
bashuf << Here
1111
2222
3333
4444
Here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment