Bash Script to Generate Password Easily
Use
head /dev/urandom | tr -dc 'A-Za-z0-9!@#$%&*' | head -c 12 in a Bash script to generate a 12-character random password.Examples
Inputlength=8
OutputaB3!x9Zq
Inputlength=12
OutputG7!kLm#2pQz$
Inputlength=16
Output4rT!v9@XzLp#2Qw%
How to Think About It
To generate a password, we want to pick random characters from a set of allowed symbols like letters, numbers, and special characters. We can get random bytes from the system, filter only allowed characters, and then cut the result to the desired length.
Algorithm
1
Get random bytes from the system source of randomness.2
Filter out only allowed characters (letters, digits, symbols).3
Cut the filtered characters to the desired password length.4
Print the resulting string as the password.Code
bash
#!/bin/bash length=12 password=$(head -c 100 /dev/urandom | tr -dc 'A-Za-z0-9!@#$%&*' | head -c "$length") echo "$password"
Output
G7!kLm#2pQz$
Dry Run
Let's trace generating a 12-character password through the code
1
Read random bytes
head /dev/urandom outputs random bytes
2
Filter allowed characters
tr -dc 'A-Za-z0-9!@#$%&*' removes unwanted characters
3
Cut to length
head -c 12 takes first 12 characters
| Operation |
|---|
| Random bytes read from /dev/urandom |
| Filtered to allowed characters only |
| First 12 characters selected as password |
Why This Works
Step 1: Get random bytes
Using /dev/urandom provides a stream of random bytes from the system.
Step 2: Filter characters
The tr -dc command deletes all characters except those we want in the password.
Step 3: Limit length
Using head -c cuts the output to the exact password length.
Alternative Approaches
Using openssl rand
bash
#!/bin/bash length=12 password=$(openssl rand -base64 15 | tr -dc 'A-Za-z0-9!@#$%&*' | head -c "$length") echo "$password"
openssl is often faster and more portable but requires openssl installed.
Using /dev/random with fold
bash
#!/bin/bash length=12 password=$(cat /dev/random | tr -dc 'A-Za-z0-9!@#$%&*' | fold -w "$length" | head -n 1) echo "$password"
/dev/random is more secure but can block if not enough entropy is available.
Complexity: O(n) time, O(n) space
Time Complexity
The script reads random bytes and filters them once, so time grows linearly with password length.
Space Complexity
Memory usage is proportional to the password length since only that many characters are stored.
Which Approach is Fastest?
Using openssl rand is usually faster and more efficient than reading from /dev/urandom directly.
| Approach | Time | Space | Best For |
|---|---|---|---|
| /dev/urandom + tr | O(n) | O(n) | Simple scripts, no extra tools |
| openssl rand | O(n) | O(n) | Faster, portable, requires openssl |
| /dev/random + fold | O(n), may block | O(n) | High security, may block if entropy low |
Always filter random bytes to allowed characters to avoid unreadable passwords.
Beginners often forget to filter characters, resulting in passwords with unreadable or control characters.