-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnew-code
More file actions
executable file
·81 lines (67 loc) · 2.29 KB
/
new-code
File metadata and controls
executable file
·81 lines (67 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/env bash
# Generate a random human readable alphanumeric code
# Environment setup - Leave this block intact
# -----------------------------------------------------------------------------
set -o pipefail # set -o errexit hides errors, don't use it
[[ ${DEBUG-} ]] && set -o xtrace
SCRIPT_DIR="$(cd "${BASH_SOURCE[0]%/*}" || exit 1; pwd)"
[[ ":${PATH}:" != *:"${SCRIPT_DIR}":* ]] && export PATH="${SCRIPT_DIR}:${PATH}"
source "${SCRIPT_DIR}/bash_modules/terminal.sh"
[[ -z ${BASH_MODULES_DIR-} ]] && echo "ERROR: terminal.sh module missing" && exit 1
function ctrlc_trap() {
log_newline
log_warning "Script interrupted. Exiting."
exit 130
}
trap ctrlc_trap SIGINT
function print_usage() {
cat <<EOF
Usage: $(basename "$0") [length]
Generate a random alphanumeric code with specific constraints.
The code is designed to be readable and avoid ambiguous characters.
Optional arguments:
length The length of the code (default: 4)
-h, --help Show this help message and exit
Code constraints:
- Alphanumeric only, no symbols
- Does not include i, l, 1, o, 0 (ambiguous characters)
- Always starts with a letter
- Only uses lower-case letters: abcdefghjkmnpqrstuvwxyz
- Only uses these numbers: 23456789
- Probability of numbers to letters is even
EOF
}
if [[ $# -gt 1 || "${1}" == "-h" || "${1}" == "--help" ]]; then
print_usage
exit 1
fi
declare length="${1:-4}"
# Validate length is numeric and positive
if [[ -n "${1}" && ! "${1}" =~ ^[1-9][0-9]*$ ]]; then
log_error "ERROR: Length must be a positive integer"
exit 1
fi
# Define character sets
declare letters="abcdefghjkmnpqrstuvwxyz"
declare numbers="23456789"
# Extend numbers to match the length of letters for even distribution
declare extended_numbers=""
while [[ ${#extended_numbers} -lt ${#letters} ]]; do
extended_numbers="${extended_numbers}${numbers:$((RANDOM % ${#numbers})):1}"
done
# Combine characters for selection
declare all_chars="${letters}${extended_numbers}"
# Generate the code
declare code=""
for ((i = 0; i < length; i++)); do
if [[ $i -eq 0 ]]; then
# Ensure the first character is a letter
char="${letters:$((RANDOM % ${#letters})):1}"
else
char="${all_chars:$((RANDOM % ${#all_chars})):1}"
fi
code="${code}${char}"
done
# Display the result
printf "%s" "${code}"
log_newline