BASH

Generate Secure Random String/Password

A bash script to generate strong, customizable random passwords or strings using /dev/urandom, suitable for secure credentials or tokens in development.

#!/bin/bash

# Usage: ./generate_password.sh [length] [include_special_chars]

DEFAULT_LENGTH=16
LENGTH=${1:-$DEFAULT_LENGTH}
INCLUDE_SPECIAL_CHARS=${2:-"false"}

# Define character sets
LOWER_CHARS="abcdefghijklmnopqrstuvwxyz"
UPPER_CHARS="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
NUM_CHARS="0123456789"
SPECIAL_CHARS="!@#$%^&*()-_+=[]{}|;:,.<>? "

ALL_CHARS="$LOWER_CHARS$UPPER_CHARS$NUM_CHARS"

if [ "$INCLUDE_SPECIAL_CHARS" = "true" ]; then
  ALL_CHARS="$ALL_CHARS$SPECIAL_CHARS"
fi

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

if [ "$LENGTH" -lt 1 ]; then
  echo "Error: Length must be at least 1."
  exit 1
fi

# Generate the random string
# Using /dev/urandom for cryptographically secure randomness
# tr -dc: delete all characters NOT in the set
# head -c: take only the first N bytes

RANDOM_STRING=$(head /dev/urandom | tr -dc "$ALL_CHARS" | head -c "$LENGTH")

echo "$RANDOM_STRING"
How it works: This script generates a cryptographically strong random string or password using `/dev/urandom` as its source of randomness. It defines character sets (lowercase, uppercase, numbers, and optionally special characters) and uses `tr -dc` to filter `urandom`'s output to include only characters from the allowed set. Finally, `head -c` truncates the output to the desired `LENGTH`. It's highly configurable and safe for generating temporary API keys, secure default credentials, or unique identifiers.

Need help integrating this into your project?

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

Hire DigitalCodeLabs