public
Last active

Split combined short shell options

  • Download Gist
split_opts.sh
Shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#!/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

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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.