Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I share options parsing code within bash functions when using getopts?
    text
    copied!<p>How can I clean up this options parsing code in a Bash function? It is copy-pasted into a number of functions that need to have a simple "-h" flag for printing usage. I would rather have a generic routine with the logical equivalent of</p> <pre><code>local prefix_opt1 local prefix_opt2 .... __handle_opts "usage message" "additional getopts flags" "prefix" </code></pre> <p>For example:</p> <pre><code>local foo_k local foo_v __handle_opts "Usage: ${FUNCNAME[0]}" [-k key -v version] widget\nBuild a widget using the key and version." "k:v:" "foo_" if [[ -z $foo_k ]] ; then foo_k="default value" fi ..... </code></pre> <p>The functions are to be "sourced" in one's dot-bashrc file.</p> <p>Here is what the code looks like (note: some of the functions do take options via flags):</p> <pre><code>function kitten_pet { local usage="Usage: ${FUNCNAME[0]} [-h] &lt;kitten&gt;\nPet the kitten." ################################################ local help=0 local error=0 local OPTIND local opt while getopts ":h" opt "$@" do case $opt in h) echo -e "$usage" help=1 break ;; \?) echo "Invalid option: -$OPTARG" error=1 break ;; esac done if [ $error -gt 0 ] || [ $help -gt 0 ] ; then return 1 fi shift $((OPTIND-1)) ################################################ if [ $# -lt 1 ] then echo -e "$usage" return 1 fi __kitten_pet "$1" } </code></pre> <p>Ordinarily I would use something like node-commander or node-optimist and write the script in JavaScript (or perhaps Python) for scripting needs but I'm trying to make Bash work this time. But Bash is bashing me.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload