I want to create a file of a specific size containing only printable strings in bash.
My first thought was to use /dev/urandom
:
dd if=/d
A conversion of @MarekNowaczyk answer to plain bash:
#!/bin/sh
(( $# )) || { echo "Pass file size as initial parameter" >&2; exit 1; }
size=$1
mk_range(){ name=$1; shift; printf -v "$name" '%b' "$(printf '\\U%08x' "$@")"; }
add_chars(){ local var; mk_range var "$@"; chars+=$var; }
## uncomment following lines to use each range.
add_chars {48..57} # 0-9 numbers
add_chars {65..90} # A-Z LETTERS
add_chars {97..122} # a-z letters
add_chars {32,{33..47},{58..64},{91..96},{123..127}} # other chars.
# convert list of characters to an array of characters.
[[ $chars =~ ${chars//?/(.)} ]] && arr=("${BASH_REMATCH[@]:1}");
alphabet_len=${#arr[@]}
# loop to print random characters
for ((i=0;i<$size;i++)); do
idx=$((RANDOM%alphabet_len))
printf '%s' "${arr[idx]}"
done
# Add a trailing new line.
echo
This code does not ensure that the resulting random distribution is uniform, it was written as an example. To ensure a random distribution in the output,
we would have to use careful arbitrary precision arithmetic to change the base (count of output characters).
Also, RANDOM is not a CSPRNG.