2

I have a script that receive parameters from user input, but can have also have parameters coming from an environment variable.

e.g. : export ADZ_DEPLOY_OPT="--from-git --rootDir XXXXXXX"

and in my script, I attempt to do something like :

$*="${ADZ_DEPLOY_OPT} $*"
while [[ $# -gt 1 ]]
do
   key="$1"
   case $key in
       --rootDir)
       ADZ_ROOT_DIR="$2"
       shift # past argument
       ;;
       --tagVersion)
       ADZ_TAG_VERSION="$2"
       shift # past argument
       ;;
       --from-git)
       ADZ_DEPLOY_FROM_GIT=1
       ;;
       *)
         # unknown option
       ;;
   esac
   shift # past argument or value
done

Except it doesn't work as it generates an error when I try to update $* to expand it with additional values - and I couldn't succeed to find a way to achieve this behavior.

The idea also is that the env variable will act as 'default' but may be overriden by what the user explicitly provide on the command line. That is with my example, if the user specify another rootDir, I want the user rootDir to be taken into account.

At last, I would like to keep long parameter names (I like being explicit) and therefore the use of getopts doesn't seem like an option.

Any help would be much appreciated !

Thanks in advance.

1
  • It is difficult to offer solutions when the problem statement is simply, "it doesn't work". Please edit your question to give a more complete description of what you expected to happen and how that differs from the actual results. See How to Ask for hints on what makes a good explanation. Commented Jul 13, 2016 at 21:29

1 Answer 1

2

Replace

$*="${ADZ_DEPLOY_OPT} $*"

with:

set -- ${ADZ_DEPLOY_OPT} "$@"

Notes:

  • As bash is designed, one cannot assign directly to $*. Assignments are done with the set builtin.

  • You want to use "$@" not $*. The form $* is subjected to word splitting and the expansion of "$@" is not.

  • From your sample value for ADZ_DEPLOY_OPT, you do need word splitting for it. If you try to put complicated arguments in ADZ_DEPLOY_OPT, this won't work: you will need to use an array instead.

Sign up to request clarification or add additional context in comments.

1 Comment

I tested you solution and it works perfectly ! Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.