From: W. Trevor King Date: Thu, 8 Dec 2011 16:01:01 +0000 (-0500) Subject: Better variable quoting in passwd-gen.sh. X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=502261e5c17d9cd974737a23c4626e09c99689bc;p=blog.git Better variable quoting in passwd-gen.sh. With the previous version, the unquoted `SET` passed to `tr` could cause problems if Bash exapanded it to a filename. Now everything is nicely quoted, using braces and everything. I also use `${paramter:-word}` for all the configuration variables, which makes it easy to override them without editing the script. For example, you can now run: $ DEVICE=/dev/urandom SET="[:alnum:][:punct:]" passwd-gen.sh 10 --- diff --git a/posts/passwd-gen.mdwn b/posts/passwd-gen.mdwn index ddbb71d..75918aa 100644 --- a/posts/passwd-gen.mdwn +++ b/posts/passwd-gen.mdwn @@ -2,9 +2,11 @@ passwords of various length and complexity. $ ./passwd-gen.sh 16 - NEmXOH2djJvUamdh + WYQwDY0fVpfouu6O Length of password: 16 - Total bytes read: 52 + Total bytes read: 73 + Device: /dev/random + Set: [:alnum:] The script is well commented, so there's not much more to say here... diff --git a/posts/passwd-gen/passwd-gen.sh b/posts/passwd-gen/passwd-gen.sh index 5ddc9de..cfccc6f 100755 --- a/posts/passwd-gen/passwd-gen.sh +++ b/posts/passwd-gen/passwd-gen.sh @@ -1,6 +1,6 @@ #!/bin/bash # -# Copyright (C) 2008-2010, William Trevor King +# Copyright (C) 2008-2011, William Trevor King # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -24,29 +24,26 @@ # to have lower NC (wastes less usable characters). For faster # DEVICEs, it's better to have a higher NC (fewer slow shell loops). -N=8 # password length -NC=4 # number of characters in a "chunk" +N="${1:-8}" # password length +NC="${NC:-4}" # number of characters in a "chunk" #SET="[:alnum:][:punct:]" # set of allowed characters (see tr(1)) -SET="[:alnum:]" -DEVICE=/dev/random # use /dev/urandom for faster, weaker passwords - -if [ -n "$1" ] -then - N="$1" -fi +SET="${SET:-[:alnum:]}" +DEVICE="${DEVICE:-/dev/random}" # use /dev/urandom for faster, weaker passwords NA=0 PWD="" -while [ "$N" -gt 0 ]; do - ALL=$(head -c "$NC" "$DEVICE") +while [ "${N}" -gt 0 ]; do + ALL=$(head -c "${NC}" "${DEVICE}") let "NA = NA + ${#ALL}" - NEW=$(echo "$ALL" | tr -d -c $SET | head -c "$N") - PWD="$PWD$NEW" + NEW=$(echo -E "${ALL}" | tr -d -c "${SET}" | head -c "${N}") + PWD="${PWD}${NEW}" let "N = N - ${#NEW}" done -echo "$PWD" +echo "${PWD}" echo "Length of password: ${#PWD}" -echo "Total bytes read: $NA" +echo "Total bytes read: ${NA}" +echo "Device: ${DEVICE}" +echo "Set: ${SET}" exit 0