A #riddle. There are two pitfalls in this code. One cloaking the other. Can you see them?
#!/bin/bash
# generate a random string of length '$bytes' using characters from
# expression '$chars'
generate_random_string() {
local bytes=${1:-24}
local chars=${2:-'A-Za-z0-9'}
dd if=/dev/urandom bs=1 count=1111 2>/dev/null \
| tr --complement --delete "$chars" \
| sed --quiet 's/\(.\{'"$bytes"'\}\).*/\1/p'
}
# function generate_random_string is meant to be used in different
# scripts in contexts like:
# generating a random password
echo "password = '$(generate_random_string)'"
# generating a 64 byte seed base64 encoded
echo "seed = '$(generate_random_string 86 'a-zA-Z0-9/+')=='"
Feedback: "You do not emphasize that the function is used by people having it sourced without knowing the code, but only knowing the description."
Yes, it is meant like that: you write a shell script and you included that function. Depending on the use of the function you'll encounter pitfalls - at least two of them.
The obvious one having been mentioned already.
@me The dd
output is limited by count=1111
and may therefore contain less than $bytes
characters among those specified by $chars
. In which case the sed
output will be empty. Anything else?
Great! You're right. That's the obvious pitfall which is cloaking the one I'm asking for (and I stumbled over).
remind me when I should publish the solution :)