Home > Mobile >  Pass argument or Ignore it if not passed BASH
Pass argument or Ignore it if not passed BASH

Time:10-31

Got an interesting scripting problem working with a Cli tool

-a means argument in this cli tool

In a Put or Post case, I must pass two arguments. So:

--verb "$1" \
    -a "$2" \
    -a "$3"

Passes in script

"put" "[\"name\"]" "testing this"

Works fine!

Then In a Get case, I must pass one argument. So:

--verb "$1" \
    -a "$2" \
    -a "$3"

Passes in script

"get" "[\"name\"]"

Of course this would fail because I MUST pass one argument but I did pass two, now that favors only the PUT operation, how do you think I handle this to make both PUT and GET work?

This is all in bash

CodePudding user response:

For more general-case handling (which will also work correctly with more than three arguments), construct an array:

#!/usr/bin/env bash
case $BASH_VERSION in '') echo "ERROR: This must be run with bash, not sh" >&2; exit 1;; esac

# unconditionally, we always have a verb; assign to a variable then shift away
args=( --verb "$1" )   # this creates an array
shift                  # makes old $2 be $1, old $3 be $2, etc

# iterate over remaining arguments and add each preceded by '-a'
for arg in "$@"; do    # iterate over all args left after the shift
  args =( -a "$arg" )  # for each, add '-a' then that arg to our array
done

# use the constructed array
runYourProgramWith "${args[@]}"

To only correctly handle $3 being optional:

--verb "$1" \
    -a "$2" \
    ${3  -a "$3" }
  • Related