BASH
Generating Random Alphanumeric String
Generate a cryptographically strong random alphanumeric string of a specified length, useful for temporary passwords or unique IDs in scripts.
#!/bin/bash
# Function to generate a random alphanumeric string
# Usage: generate_random_string [length]
generate_random_string() {
local LENGTH=${1:-32} # Default length is 32 if not provided
# Use /dev/urandom for cryptographic randomness
# tr -dc 'a-zA-Z0-9' filters out non-alphanumeric characters
# head -c $LENGTH takes the first N characters
head /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c "$LENGTH"
echo # Add a newline for clean output
}
# Example usage:
# echo "Random string (default 32 chars): $(generate_random_string)"
# echo "Random string (16 chars): $(generate_random_string 16)"
# To make it runnable directly with an argument:
if [ -n "$1" ]; then
generate_random_string "$1"
else
generate_random_string
fi
How it works: This script generates a random alphanumeric string of a specified length (defaulting to 32 characters). It leverages `/dev/urandom` for a source of high-quality randomness, pipes its output through `tr -dc 'a-zA-Z0-9'` to filter for only alphanumeric characters, and then uses `head -c` to truncate the result to the desired length. This is ideal for creating temporary passwords, unique identifiers, or secret keys within bash scripts.