Skip to content

Commit a1affea

Browse files
committed
Check getopt(1) version, fix usage note on misuse
Check whether the version of getopt(1) is the GNU one that supports preserving whitespace and special characters and long options, or the BSD one that doesn't support either (as is the default on OS X, for example). Fall back to short options only and print a warning if the old version is detected. Additionally, since set -e is used, deal with getopt(1) errors in a way that actually prints the usage information as originally intended rather than exiting right away after getopt's message. Closes: #1
1 parent 3baf7b4 commit a1affea

File tree

2 files changed

+37
-5
lines changed

2 files changed

+37
-5
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ To run this script, you will need:
1212

1313
- Bash (>= 4.x)
1414
- curl
15-
- getopt
15+
- getopt, preferrably a version that preserves quoted whitespace and long options
1616
- tput
1717
- fmt
1818
- sed, in a version that has extended regex support using either `-E` (BSD) or `-r` (GNU)

google-font-download

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -117,14 +117,46 @@ misuse_exit() {
117117
usage
118118
}
119119

120+
# Check for modern getopt(1) that quotes correctly; see #1 for rationale
121+
ret=0
122+
modern_getopt=1
123+
getopt -T >/dev/null || ret=$?
124+
if [ $ret -ne 4 ]; then
125+
modern_getopt=0
126+
fi
127+
120128
# Parse options
121-
temp=$(getopt -o f:hl:o: --long format:,help,languages:,output -n "${0:-google-font-download}" -- "$@")
122-
if [ $? != 0 ]; then
123-
echo >&2
124-
usage
129+
if [ $modern_getopt -eq 1 ]; then
130+
ret=0
131+
temp=$(getopt -o f:hl:o: --long format:,help,languages:,output -n "${0:-google-font-download}" -- "$@") || ret=$?
132+
if [ $ret -ne 0 ]; then
133+
echo >&2
134+
usage
135+
fi
136+
else
137+
cols=$(tput cols) || cols=80
138+
fmt $(( cols - 8 )) $cols >&2 <<-EOF
139+
Warning: Old getopt(1) detected.
140+
141+
Your version of getopt(1) does not correctly deal with whitespace and does not support long options. You may
142+
have to quote any special character arguments twice. For example, to download the 'Open Sans' font, use $0
143+
"'Open Sans'". See https://github.com/neverpanic/google-font-download/issues/1 for more information.
144+
145+
You should consider upgrading to a more modern version of getopt(1).
146+
147+
EOF
148+
149+
ret=0
150+
temp=$(getopt f:hl:o: $*) || ret=$?
151+
if [ $ret -ne 0 ]; then
152+
echo >&2
153+
usage
154+
fi
125155
fi
126156

127157
# Process arguments
158+
# For the non-modern getopt(1), the eval and quoting is a hack to allow users to manually specify values that have been
159+
# quoted twice.
128160
eval set -- "$temp"
129161
while true; do
130162
case "$1" in

0 commit comments

Comments
 (0)