Skip to content

Instantly share code, notes, and snippets.

@moxley
Created September 14, 2015 22:53
Show Gist options
  • Save moxley/00bdd903b282b7a101b2 to your computer and use it in GitHub Desktop.
Save moxley/00bdd903b282b7a101b2 to your computer and use it in GitHub Desktop.
Bash function for parsing script arguments for passing to sub command and sub-sub-command
# Flexible argument parsing
#
# Example:
# Command:
# ```
# ./docker/script --env=APP_ENV=development -v $(pwd)/foo:/foo docker.househappy.org/datafeed ./bin/run "puts 'hello'"
# ```
#
# Script:
# ```
# subcommand_parse_args "$@"
#
# docker run \
# --rm \
# "${OUTER_ARGS[@]}" \
# docker.househappy.org/datafeed \
# "${SUB_COMMAND[@]}"
# ```
#
# Translates to:
# ```
# ./show_args run \
# --rm \
# --env=APP_ENV=development -v $(pwd)/foo:/foo \
# docker.househappy.org/datafeed \
# ./bin/run "puts 'hello'"
# ```
function subcommand_parse_args {
OUTER_ARGS=()
SUB_COMMAND=()
in_sub_command=
short_flag=
for arg in "$@"; do
if [ "$in_sub_command" ]; then
SUB_COMMAND+=("$arg")
elif [ "$short_flag" ]; then
OUTER_ARGS+=("$arg")
short_flag=
elif [ ${arg:0} == '--' ]; then
in_sub_command=1
elif [ ${arg:0:2} == '--' ]; then
OUTER_ARGS+=("$arg")
elif [ ${arg:0:1} == '-' ]; then
OUTER_ARGS+=("$arg")
short_flag=1
else
in_sub_command=1
SUB_COMMAND+=("$arg")
fi
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment