#!/usr/bin/bash # SPDX-License-Identifier: BlueOak-1.0.0 # SPDX-FileCopyrightText: © 2021-2023 Alexander Klang # SPDX-FileNotice: License Terms # PWGEN.SH VERSION 2.2 INHUMAN # ------------------------------------------------------------------------------ # Generates 48 character passwords and prints them to "STDOUT" # # Usage: pwgen.sh [] # Where is the amount of passwords to generate (1-1000) # # Dependency: GNU Bash Shell Version 5.1 or newer # SAFEGUARDS # ------------------------------------------------------------------------------ # Abort with an error if "bash" is too old for the upcoming code if [[ -z ${BASH_VERSINFO[*]} ]] \ || (( BASH_VERSINFO[0] < 5 )) \ || (( BASH_VERSINFO[0] == 5 && BASH_VERSINFO[1] < 1 )); then echo "${0}: GNU Bash Shell Version 5.1 or newer required!" >&2 exit 1 fi # Dealing with arguments: # - Given the 1st argument is a number, it becomes "N_AMOUNT" # - If "N_AMOUNT" is too large/small, abort with an error # - When no argument is given at all, generate 1 password ("N_AMOUNT=1") # - Abort with help if anything but a number is given as 1st argument # - Any arguments but the 1st are politely ignored if [[ ${1} =~ ^[[:digit:]]+$ ]]; then # Reminder: Set number to "base 10" to strip leading 0's irritating the shell N_AMOUNT=$(( 10#${1} )) if (( N_AMOUNT < 1 || N_AMOUNT > 1000 )); then echo "${0}: The number given must be between 1 and 1000!" >&2 exit 1 fi elif [[ -z ${1} ]]; then N_AMOUNT=1 else echo "${0} generates random passwords with an easy to type structure." echo "Usage: ${0} []" echo 'Where is the amount of passwords to generate (1-1000).' exit 0 fi # MAIN CODE # ------------------------------------------------------------------------------ a_characters=( a b c d e f g h i j k l m n o p q r s t u v w x y z ) a_characters+=( 0 1 2 3 4 5 6 7 8 9 ',' '.' ':' '-' '_' ) # Run the following as often as defined in "N_AMOUNT" while (( ${n_run:=0} < N_AMOUNT )); do # Run the following 48 times until (( ${n_position:=0} == 48 )); do # Pick a random character from the pool defined in 'a_characters' n_element="$(( SRANDOM % ${#a_characters[@]} ))" # Randomly turn the chosen character into uppercase or lowercase # and add it to the password if (( SRANDOM % 2 )); then v_password+="${a_characters[${n_element}]^^}" else v_password+="${a_characters[${n_element}],,}" fi (( ++n_position )) done # Print the generated password echo "${v_password}" # Clean up lingering variables unset n_{element,position} v_password # Increment the loop's counter (( ++n_run )) done