Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Bash Snippet: Parsing Command-Line Arguments and Assigning Values

DZone's Guide to

Bash Snippet: Parsing Command-Line Arguments and Assigning Values

Developing scripts for a big data workflow and feeling the pain of using positional parameters? Not to worry. Read on to learn about using named parameters in bash.

· Big Data Zone ·
Free Resource

The open source HPCC Systems platform is a proven, easy to use solution for managing data at scale. Visit our Easy Guide to learn more about this completely free platform, test drive some code in the online Playground, and get started today.

While developing scripts for a big data workflow, I was required to develop a master and child script execution scenario. In the master as well as the child script, we were passing parameters. Given my Java background and the fact that I use a self-developed command-line argument parser, I was feeling the pain of using positional parameters.

Fortunately, using named parameters is an easy task in bash, as well. Here is a snippet:

. . .
while [[ $# -gt 0 ]]
do
    key="${1}"

    case ${key} in
    -i|--input)
        INPUTPARAM="${2}"
        shift # past argument
        shift # past value
        ;;
    -o|--output)
        OUTPUTPARAM="${2}"
        shift # past argument
        shift # past value
        ;;
    -h|--help)
        echo "Show help"
        shift # past argument
        ;;
    *)    # unknown option
        shift # past argument
        ;;
    esac
    shift
done
. . .

Reading command-line arguments is one part of the story. The second part is where we need to check the parameter for null and either assign a default value or display an error. I accomplished this using a helper function, as shown below:

. . .
PADDING_TEXT="padding"
parameterValue() {
    if [[ "${1} ${PADDING_TEXT}" == " ${PADDING_TEXT}" ]]; then
        VALUE=${2}
    else
        VALUE=${1}
    fi
    echo ${VALUE}
}
. . .
. . .
DEFAULT_INPUT_PATH="/someDirectory"
INPUT_PATH=$(parameterValue ${INPUTPARAM} ${DEFAULT_INPUT_PATH})
. . .

Correction: In my previous article, I described a function to read values from a configuration file. The function has an error: the last line of the function namely an echo command is missing. Hence, the correct snippet is:

getValueFromConfig() {
    VALUE=`grep ${1} config.sys | cut -d '=' -f 2`
    echo ${VALUE} ###<< missing statement
}

And that's it!

Managing data at scale doesn’t have to be hard. Find out how the completely free, open source HPCC Systems platform makes it easier to update, easier to program, easier to integrate data, and easier to manage clusters. Download and get started today.

Topics:
bash ,big data ,command-line ,named parameters

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}