Bash Processing of Command Line Parameters that Include Spaces: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 5: Line 5:
=Overview=
=Overview=


This page documents a coding pattern to be used when some of the command line parameters need to be processed in the wrapper shell script, and the rest of the parameter, that may include spaces, need to be passed unchanged to the target process. The pattern uses a special separator character, that is injected between the arguments to be passed to the lower layer, followed by the recreation of the command line with [[bash set|set]].  
This page documents a shell coding pattern to be used when some of the command line parameters need to be processed in the wrapper shell script, and the rest of the parameter, which may include spaces, are passed unchanged to the target process. The pattern uses a special separator character, that is injected between the arguments to be forwarded to the lower layer, followed by the recreation of the command line with [[bash set|set]].  


Double-quote enclosed and single-quote encloses command line arguments that contain spaces are consistently handled.
The pattern handles consistently both double-quote enclosed and single-quote encloses command line arguments that contain spaces.


<syntaxhighlight lang='bash'>
<syntaxhighlight lang='bash'>

Revision as of 01:42, 24 September 2017

Internal

Overview

This page documents a shell coding pattern to be used when some of the command line parameters need to be processed in the wrapper shell script, and the rest of the parameter, which may include spaces, are passed unchanged to the target process. The pattern uses a special separator character, that is injected between the arguments to be forwarded to the lower layer, followed by the recreation of the command line with set.

The pattern handles consistently both double-quote enclosed and single-quote encloses command line arguments that contain spaces.

# ...

local args
local separator=$'\x1f' # US - unit separator

while [ -n "$1" ]; do

    if [ "$1" = "..." ]; then

        #
        # process arguments that make sense at this layer
        #
        echo "processing $1 at this level ..."

        # ...

    else

        #
        # ... and accumulate the rest of the arguments between special separator characters
        #
        [ -z "${args}" ] && args="$1" || args="${args}${separator}$1"
    fi
    shift
done

#
# re-assemble the command line, by re-initializing the positional parameters, and pass it to the underlying process
#
IFS=${separator}
set - ${args}
IFS="$(printf ' \t\n')" # restore the standard separators

#
# Use "$@" built-in variable, which encloses each positional parameter in its own set of double quotes
#

java -cp ... io.novaordis.playground.Main "$@"