← Back to all snippets
BASH

Generate Random Alphanumeric String for Passwords or Keys

Create secure, random alphanumeric strings with a specified length using '/dev/urandom' and 'tr'. Ideal for temporary passwords, API keys, or unique identifiers in scripts.

#!/bin/bash
LENGTH=${1:-16} # Default length is 16 if not provided

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

if [ "$LENGTH" -le 0 ]; then
    echo "Error: Length must be greater than zero."
    exit 1
fi

head /dev/urandom | tr -dc A-Za-z0-9_ | head -c "$LENGTH" ; echo
How it works: This script generates a random alphanumeric string of a specified length (defaulting to 16 characters if no argument is provided). It leverages `/dev/urandom` for a source of high-quality random data, pipes it through `tr -dc A-Za-z0-9_` to keep only alphanumeric characters and underscores, and then uses `head -c` to truncate the output to the desired length, followed by a newline.

Need help integrating this into your project?

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

Hire DigitalCodeLabs