-
Notifications
You must be signed in to change notification settings - Fork 0
/
random_string.sh
62 lines (57 loc) · 1.31 KB
/
random_string.sh
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
#!/bin/bash
###############
# Description #
###############
#
# Generate a random string
function get_character_form_ascii() {
local type=$1
local num=$2
case $type in
"digit")
# optimize range to hit
local num=$((RANDOM % 58))
if [ $num -ge 48 ] && [ $num -le 57 ]; then
printf "\x$(printf "%x" $num)"
fi
;;
"letter")
if [ $num -ge 65 ] && [ $num -le 90 ]; then
printf "\x$(printf "%x" $num)"
elif [ $num -ge 97 ] && [ $num -le 122 ]; then
printf "\x$(printf "%x" $num)"
fi
;;
*)
if [ $num -ge 48 ] && [ $num -le 57 ]; then
printf "\x$(printf "%x" $num)"
elif [ $num -ge 65 ] && [ $num -le 90 ]; then
printf "\x$(printf "%x" $num)"
elif [ $num -ge 97 ] && [ $num -le 122 ]; then
printf "\x$(printf "%x" $num)"
fi
;;
esac
}
function generate_random_string() {
local type=$1
local str_len=$2
for i in $(seq "$str_len"); do
until [ "${str[$i]}" ]; do
local num=$((RANDOM % 123))
str[$i]=$(get_character_form_ascii "$type" $num)
done
done
printf "%s" "${str[@]}"
}
function main_process() {
local str_len=$1
[ -z "$str_len" ] && str_len=8
local arg=$2
case $arg in
"") generate_random_string "both" "$str_len" ;;
*) generate_random_string "$arg" "$str_len" ;;
esac
}
main_process "$@"
echo