YubiKey-Guide icon indicating copy to clipboard operation
YubiKey-Guide copied to clipboard

$@ needs to be quoted for safe usage

Open charles-dyfis-net opened this issue 2 years ago • 1 comments

#!/usr/bin/env bash
test ! "$@" && echo "Specify a key." && exit 1
KEYGRIPS="$(gpg --with-keygrip --list-secret-keys $@ | grep Keygrip | awk '{print $3}')"

Consider instead:

#!/usr/bin/env bash
(( $# )) || { echo "Specify a key." >&2; exit 1; }
KEYGRIPS=$(gpg --with-keygrip --list-secret-keys "$@" | awk '/Keygrip/ { print $3 }')
  • "$@" expands to an arbitrary number of arguments (which can be zero -- in which case test ! is treated like test -n '!' and has a truthy result), but test ! "$@" only works in a reasonable way if it expands to exactly one argument. test ! "$*", concatenating all arguments together into a single string, is probably closer to the original intended meaning; but since the shell is guaranteed to be bash, (( $# )) is both terser and more readable.
  • When unquoted, $@ acts exactly like an unquoted $*, with several undesirable behaviors: It doesn't honor original quoting, but instead word-splits the argument list and then attempts to process each item resulting from that as a glob. Using "$@" passes the original argument list through exactly as-is.

charles-dyfis-net avatar Jun 21 '22 22:06 charles-dyfis-net

Thanks for the suggestion - would you mind sending a PR to make the necessary change?

drduh avatar Aug 21 '22 18:08 drduh