gen_string.sh (1881B)
1 #!/bin/sh 2 # 3 # script 4 5 DICT='/usr/share/dict/british-english' 6 LENGTH_ERROR='String length must be a number between 1 and 64.' 7 8 is_integer() { 9 case "${1}" in 10 (*[!0123456789]*) return 1 ;; 11 ('') return 1 ;; 12 (*) return 0 ;; 13 esac 14 } 15 16 main() { 17 while :; do 18 # get string type 19 printf '%s\n' 'Type of string (0 = random, 1 = phrase)?: ' 20 read -r string_type 21 # incorrect input 22 { [ ! "${string_type}" = '0' ] && [ ! "${string_type}" = '1' ] ; } && printf '%s\n' 'String type must be a number between 0 and 1.' && continue 23 break 24 done 25 26 # get string length 27 while :; do 28 printf '%s\n' "If you're generating a phrase, it's recommended to use a middling length, because it's very time consuming or even impossible to generate a phrase if the length is very low or very high." 29 printf '%s\n' 'Length of string (1-64)?: ' 30 read -r length 31 # test whether input is number 32 ! is_integer "${length}" && printf '%s\n' "${LENGTH_ERROR}" && continue 33 # test whether input is within range 34 { [ "${length}" -lt 1 ] || [ "${length}" -gt 64 ] ; } && printf '%s\n' "${LENGTH_ERROR}" && continue 35 break 36 done 37 38 # generate string 39 string='' 40 # generate random string via /dev/urandom and tr 41 if [ "${string_type}" = '0' ]; then 42 string="$(</dev/urandom tr -dc 'A-Za-z0-9!"#$%&'\''()*+,-./:;<=>?@[\]^_`{|}~' | head -c "${length}"; printf '\n')" 43 printf '%s\n' "${string}" 44 # generate random phrase by pulling words from dictionary 45 elif [ "${string_type}" = '1' ]; then 46 while :; do 47 string="$(grep -v "'s\|[[:upper:]]" "${DICT}" | shuf -n 4 | tr -d '\n')" 48 [ ${#string} -eq "${length}" ] && printf '%s\n' "${string}" && break 49 done 50 fi 51 52 return 0 53 } 54 55 main "${@}"