Thursday, February 23, 2012

bash parameter parsing from data

I had to write a script where parameters are read form a shell script. At first I thought writing a shell function to extract values would be nice and if it could allow shell syntax and quoting that would also be nice so here it is:
get_param() {
    local paramname="$1"
    local result=""

    local IFS="
"
    for line in $SCRIPT_DATA; do
        unset IFS
        line=${line%%#*} # removed any comments
        case "$line" in
        *"$paramname"=*)
            # lets check we are not matching only suffix of param
            case `echo ${line%%=*}` in
            $paramname) result=`eval "$line ; echo \"\\${$paramname}\""` ;;
        esac
        ;;
        esac
    done
    echo -n "$result"
}

if SCRIPT DATA is like:
param1=value1
hostname=`hostname`
paramN=valueN


get_param hostname would return the hostname of machine.

If SCRIPT_DATA is like:
hostname='`hostname`'

get_param hostname would return `hostname` avoiding expansion.

A couple of limitations:
  • control structures are not regarded
  • not secure (run only through trusted code)
  • multi-line expressions not supported
After all I decided complexity isn't worth it so just source/eval the script data. If necessary use grep/sed to filter it.
Maybe it would have been more useful if I could split the script data to complete shell expressions but I'm not sure added complexity will be worth it either.

In any case I just put this function here to not lose it. Similar use cases pop from time to time...

No comments:

Post a Comment