Created
March 27, 2012 23:17
-
-
Save jacobsandlund/2221367 to your computer and use it in GitHub Desktop.
Split combined short shell options
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# This shows how to handle combined short options along with | |
# other long and short options. It does so by splitting them | |
# apart (e.g. 'tar -xvzf ...' -> 'tar -x -v -z -f ...') | |
while test $# -gt 0 | |
do | |
case $1 in | |
# Normal option processing | |
-h | --help) | |
# usage and help | |
;; | |
-v | --version) | |
# version info | |
;; | |
# ... | |
# Special cases | |
--) | |
break | |
;; | |
--*) | |
# error unknown (long) option $1 | |
;; | |
-?) | |
# error unknown (short) option $1 | |
;; | |
# FUN STUFF HERE: | |
# Split apart combined short options | |
-*) | |
split=$1 | |
shift | |
set -- $(echo "$split" | cut -c 2- | sed 's/./-& /g') "$@" | |
continue | |
;; | |
# Done with options | |
*) | |
break | |
;; | |
esac | |
# for testing purposes: | |
echo "$1" | |
shift | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
getopts
only handles short options, andgetopt
might not be available on some systems. In cases where long options are necessary and adding agetopt
dependency needs to be avoided, this method can be used. The downside is that you miss out on the additional functionality ofgetopt
. On the other hand, syncing the options supplied togetopt
and the option handling code (usually a while + case) can also become frustrating, and this avoids that pain.