Menu

Generate Nanoids in Bash

Resources  |  Generate Nanoids in Bash

Generating a Nanoid in Bash involves creating a script that utilizes available tools to generate random, URL-safe characters. One effective way to achieve this is by using /dev/urandom for random bytes and tr to map these bytes to the desired alphabet.

Here's a step-by-step guide to generating a Nanoid in Bash:

Example Script

Below is a Bash script that generates a Nanoid of a specified length:

#!/bin/bash

# Define the alphabet used for Nanoid generation
ALPHABET="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"

# Define the length of the Nanoid
LENGTH=21

# Function to generate a Nanoid
generate_nanoid() {
  local nanoid=""
  for _ in $(seq 1 $LENGTH); do
    # Generate a random byte and map it to a character from the alphabet
    local index=$(head -c 1 /dev/urandom | od -An -tu1 | awk '{print $1 % 64}')
    nanoid="${nanoid}${ALPHABET:$index:1}"
  done
  echo "$nanoid"
}

# Generate and print the Nanoid
nanoid=$(generate_nanoid)
echo "Generated Nanoid: $nanoid"

Explanation

  1. Alphabet:

    • The ALPHABET variable contains characters that the Nanoid will consist of. It includes uppercase letters, lowercase letters, digits, and the symbols '-' and '_'.
  2. Length:

    • The LENGTH variable defines the length of the Nanoid to be generated. You can adjust this value to create Nanoids of different lengths.
  3. Random Byte Generation:

    • head -c 1 /dev/urandom: Reads a single random byte from /dev/urandom.
    • od -An -tu1: Converts the byte to an unsigned decimal number.
    • awk '{print $1 % 64}': Maps the number to an index within the range of the alphabet (0-63).
  4. Nanoid Construction:

    • The script loops for the number of characters specified by LENGTH, generates a random index for each character, and appends the corresponding character from the ALPHABET to the Nanoid string.
  5. Output:

    • The generated Nanoid is printed to the console.

Usage

  1. Save the script to a file, e.g., generate_nanoid.sh.
  2. Make the script executable:
    chmod +x generate_nanoid.sh
    
  3. Run the script:
    ./generate_nanoid.sh
    

Customization

  • Alphabet: Modify the ALPHABET variable if you need a different set of characters.
  • Length: Change the LENGTH variable to generate Nanoids of different lengths.

Considerations

  • Randomness: The script uses /dev/urandom, which provides a good source of randomness suitable for most purposes. If higher security is needed, consider using /dev/random, though it may block if there is insufficient entropy.
  • Efficiency: This script reads one byte at a time and is not highly optimized. For higher performance requirements, more efficient methods or languages may be necessary.

This script provides a basic yet effective way to generate Nanoids in Bash, leveraging the powerful tools available in Unix-like environments.