aboutsummaryrefslogtreecommitdiffstats
path: root/unix/gen-pass.sh
blob: 4718b0c6943f159fc9a0cc8827266b3753021ff4 (plain)
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
#!/bin/sh
#
# Copyright (c) 2019 Aaron LI
# MIT License
#
# Generate random passwords.
#
# Credit:
# * How to generate a random string?
#   https://unix.stackexchange.com/a/230676
# * password-store:
#   http://www.passwordstore.org/
#

# usage: generate ${characters} ${length}
generate() {
    local characters="$1"
    local length="$2"
    env LC_ALL=C tr -dc "${characters}" </dev/urandom |
        head -c ${length}
}

usage() {
    cat << _EOF_
Generate random passwords.

usage:
    ${0##*/} [-n] [-l length] [count]

options:
    -n : no symbols, i.e., only alphabets and numbers
    -l length : password length (default: 16)
    count : number of passwords to generate (default: 1)
_EOF_

    exit 1
}

main() {
    local characters="[:graph:]"
    local length=16
    local count=1

    while getopts :hl:n opt; do
        case ${opt} in
        h)
            usage
            ;;
        l)
            length="${OPTARG}"
            ;;
        n)
            characters="[:alnum:]"
            ;;
        \?)
            echo "Invalid option -${OPTARG}"
            usage
            ;;
        :)
            echo "Option -${OPTARG} requires an argument"
            usage
            ;;
        esac
    done

    shift $((${OPTIND} - 1))
    if [ $# -eq 0 ]; then
        :
    elif [ $# -eq 1 ]; then
        count="$1"
    else
        usage
    fi

    for i in $(seq ${count}); do
        generate "${characters}" ${length}
        echo
    done
}

main "$@"