I wish to have long and short forms of command line options invoked using my shell script.
I know that getopts
can be used, but like in Perl, I have not
Take a look at shFlags which is a portable shell library (meaning: sh, bash, dash, ksh, zsh on Linux, Solaris, etc.).
It makes adding new flags as simple as adding one line to your script, and it provides an auto generated usage function.
Here is a simple Hello, world!
using shFlag:
#!/bin/sh
# source shflags from current directory
. ./shflags
# define a 'name' command-line string flag
DEFINE_string 'name' 'world' 'name to say hello to' 'n'
# parse the command-line
FLAGS "$@" || exit 1
eval set -- "${FLAGS_ARGV}"
# say hello
echo "Hello, ${FLAGS_name}!"
For OSes that have the enhanced getopt that supports long options (e.g. Linux), you can do:
$ ./hello_world.sh --name Kate
Hello, Kate!
For the rest, you must use the short option:
$ ./hello_world.sh -n Kate
Hello, Kate!
Adding a new flag is as simple as adding a new DEFINE_ call
.