Bash Script to Generate Random String Easily
head -c 12 /dev/urandom | tr -dc A-Za-z0-9 | head -c 12 in Bash to generate a random 12-character string.Examples
How to Think About It
/dev/urandom, then filter out unwanted characters using tr, and finally select the desired number of characters with head -c.Algorithm
Code
#!/bin/bash length=12 random_string=$(head -c 100 /dev/urandom | tr -dc A-Za-z0-9 | head -c "$length") echo "$random_string"
Dry Run
Let's trace generating a random string of length 4 through the code
Read random bytes
head -c 100 /dev/urandom outputs random bytes like '\x4a\x7f\x21...'
Filter characters
tr -dc A-Za-z0-9 removes non-alphanumeric characters, leaving 'Z1xQ...' sequence
Cut to length
head -c 4 takes first 4 characters: 'Z1xQ'
| Step | Operation | Result |
|---|---|---|
| 1 | Read random bytes | \x4a\x7f\x21\x5a\x31\x78\x51... |
| 2 | Filter to alphanumeric | Z1xQ... |
| 3 | Cut to length 4 | Z1xQ |
Why This Works
Step 1: Read random bytes
The command head -c 100 /dev/urandom reads raw random data from the system.
Step 2: Filter characters
Using tr -dc A-Za-z0-9 removes all characters except letters and digits, making the string readable.
Step 3: Limit length
The head -c command cuts the output to the desired number of characters.
Alternative Approaches
openssl rand -base64 12 | tr -dc A-Za-z0-9 | head -c 12
cat /dev/urandom | tr -dc A-Za-z0-9 | fold -w 12 | head -n 1
for i in {1..12}; do printf '%x' $((RANDOM%16)); done
Complexity: O(n) time, O(n) space
Time Complexity
The script reads and processes a fixed number of bytes proportional to the desired string length, so time grows linearly with string length.
Space Complexity
Memory usage grows linearly with the output string length since it stores the filtered characters.
Which Approach is Fastest?
Using head /dev/urandom with tr is fast and simple; openssl rand may be faster but requires extra software.
| Approach | Time | Space | Best For |
|---|---|---|---|
| head /dev/urandom + tr | O(n) | O(n) | Simple, no extra tools |
| openssl rand | O(n) | O(n) | Faster, requires OpenSSL |
| Bash $RANDOM loop | O(n) | O(n) | Hex strings, no external commands |