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

Hortonworks Sandbox for HDP and HDF is your chance to get started on learning, developing, testing and trying out new features. Each download comes preconfigured with interactive tutorials, sample data and developments from the Apache community.

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!

Hortonworks Community Connection (HCC) is an online collaboration destination for developers, DevOps, customers and partners to get answers to questions, collaborate on technical articles and share code examples from GitHub.  Join the discussion.

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 }}