2

I want to dynamically generate pretty long bash command depending on the command line options. Here is what I tried:

CONFIG_PATH=""

#Reading CONFIG_PATH from getopts if supplied

SOME_OPT=""
if [ ! -z "$CONFIG_PATH" ]; then
    SOME_OPT="-v -s -cp $CONFIG_PATH"
fi

some_bash_command $SOME_OPT

The point here is that I want to pass 0 arguments to the some_bash_command if no arguments were passed to the script. In case there were some arguments I want to pass them.

It works fine, but the problem is that this approach looks rather unnatural to me.

What would be a better yet practical way to do this?

1 Answer 1

5

Your approach is more-or-less the standard one; the only significant improvement that I'd recommend is to use an array, so that you can properly quote the arguments. (Otherwise your command can horribly misbehave if any of the arguments happen to include special characters such as spaces or asterisks.)

So:

SOME_OPT=()
if [ ! -z "$CONFIG_PATH" ]; then
    SOME_OPT=(-v -s -cp "$CONFIG_PATH")
fi

some_bash_command "${SOME_OPT[@]}"
Sign up to request clarification or add additional context in comments.

Comments

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.