Skip to content

Instantly share code, notes, and snippets.

@jacobsandlund
Created March 27, 2012 23:17
Show Gist options
  • Save jacobsandlund/2221367 to your computer and use it in GitHub Desktop.
Save jacobsandlund/2221367 to your computer and use it in GitHub Desktop.
Split combined short shell options
#!/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
@jacobsandlund
Copy link
Author

getopts only handles short options, and getopt might not be available on some systems. In cases where long options are necessary and adding a getopt dependency needs to be avoided, this method can be used. The downside is that you miss out on the additional functionality of getopt. On the other hand, syncing the options supplied to getopt and the option handling code (usually a while + case) can also become frustrating, and this avoids that pain.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment