HiveBrain v1.2.0
Get Started
← Back to all entries
patternbashMinor

Functions for scanning command line options

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
functionslineoptionsforcommandscanning

Problem

I know that getopts is available but I wanted to write my own as a way of improving my bash. Below I show two function definitions and an example of the use of them in a bash script. Finally I show the output of the script.

Please comment.

#!/bin/bash
# Produce a string variable which can be used by function isoption
# to give calling scripts an easy way to determine what options are
# are provided in its command line regardless of their order.  
# Call this function as:
#
#   mygetopts "$@"
#
# Non-option arguments in the command line of the caller are
# passed back to the caller in array NONOPTARGS and can be used like this:
#
#   name=NONOPTARGS[0]
#
# NOTE: Option globbing is not allowed

function mygetopts ()
{ 
# Initialize a string variable which will be made to contain all
# option names in "$@".  Since this string will be used by function
# isoption a weird variable name is used to avoid collision with
# variable names in calling script since it cannot be made local.

    O1P2T3I4O5N6="-"    # O1P2T3I4O5N6 is avaiable to caller
    declare -i i=0      # i is local to function

    if [[ "$1" == "-h" || "$1" == "--help" ]]; then
        echo "Usage: $0 \"\$@\"" >&2
        return 1
    fi

    for arg in "$@" ; do    # arg will be each positional parameter
        if [[ ${arg:0:1} == - ]]    # if $arg begins with -
            # Pack all option names separated by -
            then O1P2T3I4O5N6=${O1P2T3I4O5N6}${arg:1}-

            else NONOPTARGS[i++]=$arg
        fi
        #echo "O1P2T3I4O5N6  =$O1P2T3I4O5N6"
        #echo "NONOPTARGS = ${NONOPTARGS[@]}"
    done
    return 0
}

function isoption ()
{

    if [[ $O1P2T3I4O5N6 =~ ^.*-${1}-.*$ ]] 
        then return 0
        else return 1 
    fi
}


```
#!/bin/bash
# Example of using functions mygetopts and isoption to provide easy
# access to all command line options as well as non-option arguments
# regardless of their order.
#
# To use these functions place the file MYFUNCTIONS in your $HOM

Solution

The bash code all looks reasonably fine to me.

The -h and --help output doesn't look right (it will print the actual parameters passed, but should print the list of allowable options/parameters?)

Options like --this-will-break won't work with --will or --break.

I'm not clear if parameters with spaces in them will work, as in: testmygetopts "this is one argument"

I think 'isoption' could be simplifed to just be the [[ ]] expression (since it will return 0 or 1 already).

Context

StackExchange Code Review Q#2827, answer score: 3

Revisions (0)

No revisions yet.