Skip to content

Commit f40ffce

Browse files
committed
Added support for getopts with fallback on getopt.
1 parent a20f320 commit f40ffce

File tree

1 file changed

+41
-15
lines changed

1 file changed

+41
-15
lines changed

virtualenvwrapper.sh

Lines changed: 41 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,12 @@ virtualenvwrapper_show_workon_options () {
291291
# (cd "$WORKON_HOME"; find -L . -depth 3 -path '*/bin/activate') | sed 's|^\./||' | sed 's|/bin/activate||' | sort
292292
}
293293

294+
295+
# test if a given command exists
296+
command_exists () {
297+
command -v "$1" &> /dev/null ;
298+
}
299+
294300
_lsvirtualenv_usage () {
295301
echo "lsvirtualenv [-blh]"
296302
echo " -b -- brief mode"
@@ -302,23 +308,43 @@ _lsvirtualenv_usage () {
302308
#
303309
# Usage: lsvirtualenv [-l]
304310
lsvirtualenv () {
305-
typeset -a args
306-
args=($(getopt blh "$@"))
307-
if [ $? != 0 ]
311+
312+
typeset long_mode=true
313+
if command_exists getopts
308314
then
309-
_lsvirtualenv_usage
310-
return 1
315+
# Use getopts when possible
316+
OPTIND=1
317+
while getopts ":blh" opt "$@"
318+
do
319+
case "$opt" in
320+
l) long_mode=true;;
321+
b) long_mode=false;;
322+
h) _lsvirtualenv_usage;
323+
return 1;;
324+
?) echo "Invalid option: -$OPTARG" >&2;
325+
_lsvirtualenv_usage;
326+
return 1;;
327+
esac
328+
done
329+
else
330+
# fallback on getopt for other shell
331+
typeset -a args
332+
args=($(getopt blh "$@"))
333+
if [ $? != 0 ]
334+
then
335+
_lsvirtualenv_usage
336+
return 1
337+
fi
338+
for opt in $args
339+
do
340+
case "$opt" in
341+
-l) long_mode=true;;
342+
-b) long_mode=false;;
343+
-h) _lsvirtualenv_usage;
344+
return 1;;
345+
esac
346+
done
311347
fi
312-
typeset long_mode=true
313-
for opt in $args
314-
do
315-
case "$opt" in
316-
-l) long_mode=true;;
317-
-b) long_mode=false;;
318-
-h) _lsvirtualenv_usage;
319-
return 1;;
320-
esac
321-
done
322348

323349
if $long_mode
324350
then

0 commit comments

Comments
 (0)