← Back to all snippets
BASH

Generate Strong Random Passwords/Tokens

Generate secure, random passwords or tokens using /dev/urandom and head in Bash, essential for temporary credentials or unique identifiers.

#!/bin/bash

# Default length
LENGTH=16

# Parse arguments for length
while [[ "$#" -gt 0 ]]; do
    case "$1" in
        -l|--length) LENGTH="$2"; shift ;;
        *) echo "Unknown parameter passed: $1"; exit 1 ;;
    esac
    shift
done

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

# Generate a random string using /dev/urandom and base64 encoding
# /dev/urandom provides high-quality random data
# head -c N limits the bytes read
# base64 encodes the binary data into a printable string
# tr -dc 'A-Za-z0-9-_' removes any characters not in the specified set
# head -c $LENGTH takes only the first $LENGTH characters

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

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

# Example usage:
# ./generate_password.sh
# ./generate_password.sh -l 32
How it works: This script generates a strong, random string suitable for use as a password or API token. It leverages the high-quality random data from `/dev/urandom`, encodes it to a printable format using `base64`, and then filters the characters to include alphanumeric, hyphen, and underscore using `tr`. Finally, `head -c` truncates the string to the desired length (default 16, configurable via `-l` or `--length`). This is invaluable for generating secure, unique identifiers for various development and security tasks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs