-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrand-string
More file actions
executable file
·80 lines (67 loc) · 1.52 KB
/
rand-string
File metadata and controls
executable file
·80 lines (67 loc) · 1.52 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
#!/usr/bin/env bash
set -euo pipefail
function main() {
local POSITIONAL_ARGS=()
local n_chars=32
while [ "$#" -gt 0 ]; do
case "$1" in
-h | --help)
print-usage
exit 0
;;
-n | --num)
require-named-arg "$@"
n_chars="$2"
shift
shift
;;
-*)
print-error "Error: Unknown option: $1"
;;
*)
POSITIONAL_ARGS+=("$1")
shift
;;
esac
done
local first_arg="${POSITIONAL_ARGS[0]:-}"
if [ -n "$first_arg" ]; then
n_chars="$first_arg"
fi
n_chars="${n_chars^^}"
if [[ "$n_chars" =~ ^[1-9][0-9]*[KMGT]?$ ]]; then
rand-str "$n_chars"
else
print-error "Error: number argument must be a positive integer with optional suffix (eg. 12, 64, 8K, 1M...)"
fi
}
function require-named-arg() {
if [ -z "$2" ]; then
print-error "Error: Argument for $1 is missing" >&2
fi
}
function rand-str() {
openssl rand -base64 "$1" | xargs printf "%s" | head -c "$1"
}
function print-error() {
echo "$1" >&2
echo "" >&2
print-usage >&2
exit 1
}
function print-usage() {
local script_name
script_name="$(basename "$0")"
echo "Usage: $script_name [...options] [NUM_CHARS]"
echo ""
echo "Options:"
echo " -h, --help Display this help message."
echo " -n, --num Number of characters to generate."
echo " Default: 32"
echo ""
echo "Examples:"
echo " $script_name 16"
echo " $script_name -n 8 16 # outputs 16 random characters"
echo " $script_name -n 32 | xclip -sel clip"
}
main "$@"