Initial commit
This commit is contained in:
39
scripts/random-words
Executable file
39
scripts/random-words
Executable file
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env bash
|
||||
# This function will create a random word pair with an underscore separator ex. turtle_ladder
|
||||
# It accepts one optional argument (an integer) (the number of words to return)
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
random_words() {
|
||||
local num="${1:-2}"
|
||||
local -a arr
|
||||
local word
|
||||
|
||||
# Validate input
|
||||
if ! [[ "$num" =~ ^[0-9]+$ ]] || [[ "$num" -lt 1 ]]; then
|
||||
echo "[ERROR] Argument must be a positive integer" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Check if dictionary file exists
|
||||
if [[ ! -f /usr/share/dict/words ]]; then
|
||||
echo "[ERROR] Dictionary file /usr/share/dict/words not found" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
for ((i=0; i<num; i++)); do
|
||||
# Get random word and sanitize in one pass
|
||||
word=$(shuf -n1 /usr/share/dict/words | tr -d '-_' | tr '[:upper:]' '[:lower:]')
|
||||
arr+=("$word")
|
||||
done
|
||||
|
||||
# Join array with underscores
|
||||
local IFS="_"
|
||||
echo "${arr[*]}"
|
||||
}
|
||||
|
||||
# Allow this file to be executed directly if not being sourced
|
||||
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
|
||||
random_words "$@"
|
||||
exit $?
|
||||
fi
|
||||
Reference in New Issue
Block a user