BASH

Generate Random Alphanumeric String

A simple Bash script to generate a cryptographically strong, random alphanumeric string of a specified length, useful for temporary passwords, API keys, or unique identifiers.

#!/bin/bash

# This script generates a random alphanumeric string of a specified length.

LENGTH=${1:-16} # Default length is 16 if no argument is provided

if ! [[ "$LENGTH" =~ ^[0-9]+$ ]]; then
    echo "Error: Length must be a positive integer."
    exit 1
fi

if [ "$LENGTH" -eq 0 ]; then
    echo "Error: Length cannot be zero."
    exit 1
fi

# Generate a random string using /dev/urandom
# tr -dc 'a-zA-Z0-9': delete all characters not in 'a-z', 'A-Z', or '0-9'
# head -c $LENGTH: take only the first $LENGTH characters

RANDOM_STRING=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c "$LENGTH")

echo "Generated Random String (Length: $LENGTH): $RANDOM_STRING"

exit 0
How it works: This Bash script generates a cryptographically strong, random alphanumeric string of a user-defined length (defaulting to 16 if none is provided). It leverages `/dev/urandom`, a source of high-quality random data provided by the operating system. The output from `/dev/urandom` is piped to `tr -dc A-Za-z0-9` to filter out all non-alphanumeric characters, ensuring the resulting string contains only letters and numbers. Finally, `head -c $LENGTH` truncates the output to the desired length. This snippet is ideal for creating temporary passwords, generating unique session tokens, or secure API keys within your web development workflows.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs