BashFunctionArgumentParsing

16th June 2016 at 4:51pm
CodeSnippets
#!/bin/bash
set -eu -o pipefail

function log_var () {
    local var
    for var; do echo "$var=${!var}"; done
}

function my_func () {
    local args="pos_arg1 pos_arg2 pos_arg3"
    local $args named_arg1= named_arg2=defval named_arg3= named_arg4=
    for arg in $args; do declare $arg="$1"; shift; done
    [[ $# -gt 0 ]] && local "$@"

    # Function gubbins here
    log_var pos_arg1 pos_arg2 pos_arg3 \
            named_arg1 named_arg2 named_arg3 named_arg4
}

# Example:
my_func "hello" "world" "third arg" \
        named_arg3="fish fingers" \
        named_arg1=kittens

Output from the above example:

nicolaw@mycomputer~ $ ./example.sh
pos_arg1=hello
pos_arg2=world
pos_arg3=third arg
named_arg1=kittens
named_arg2=defval
named_arg3=fish fingers
named_arg4=