How to Create a Token in Bash Script

In a Bash script, to generate a similar secure token, we can use /dev/urandom or openssl to generate random bytes and construct a character set based on the provided options. The following is an example of a Bash function that emulates the functionality of the JavaScript function you provided:

#!/bin/bash

generate_token() {
  local length="$1"
  local options=${2:-""}

  local uppercase=${options//,uppercase/}
  local lowercase=${options//,lowercase/}
  local numbers=${options//,numbers/}

  # Set default values
  if [ -z "$uppercase" ]; then uppercase=true; fi
  if [ -z "$lowercase" ]; then lowercase=true; fi
  if [ -z "$numbers" ]; then numbers=true; fi

  local charset=""
  if [ "$uppercase" = true ]; then
    charset+='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  fi
  if [ "$lowercase" = true ]; then
    charset+='abcdefghijklmnopqrstuvwxyz'
  fi
  if [ "$numbers" = true ]; then
    charset+='0123456789'
  fi

  if [ -z "$charset" ]; then
    echo "Error: At least one character set must be selected." >&2
    return 1
  fi

  local token=""
  while [ ${#token} -lt "$length" ]; do
      # Generate a random number between 0 and the length of the charset
      local random_index=$(( ($RANDOM % 32768) % ${#charset} ))
      token+=${charset:$random_index:1}
  done

  echo "$token"
}

# Example usage:
# generate_token 16 "uppercase,true,lowercase,true,numbers,true"

This function accepts two parameters: length and options. The options parameter is a string that includes configurations for whether to include uppercase letters, lowercase letters, and numbers, separated by commas. If the options parameter is not provided, all options default to true.

Please note that this Bash function uses $RANDOM to generate random numbers, which may not be secure enough for scenarios with high security requirements. For applications that require higher security, consider using openssl to generate random bytes:

generate_token_secure() {
  local length="$1"
  local options=${2:-""}

  # ... (same as above for setting default values and charset)

  local token=""
  while [ ${#token} -lt "$length" ]; do
      # Generate a random byte using openssl
      local random_byte=$(openssl rand -hex 1)
      local random_index=$(( 16#${random_byte} % ${#charset} ))
      token+=${charset:$random_index:1}
  done

  echo "$token"
}

In this secure version, we use openssl rand -hex 1 to generate a random hexadecimal byte, which is then converted to a decimal number to index the character set. This provides stronger randomness.