Andreas
Andreas

Reputation: 569

bash: expanding function arguments

I have an issue with a bash function for a shell script i'm writing. The function is as follows:

do_command() {
  if [[ $DRY_RUN ]]; then
    echo $@
  else
    $@
  fi
}

Function is simple, if the DRY_RUN flag is set we just print the method otherwise it is executed. This works well for most commands except git tag command that I have tried different versions of like:

do_command git tag -a $NEW_VERSION -m '$INPUT_COMMENT'

That actually executes the tag command, but give the comment $INPUT_COMMENT

I have tried 2 other versions that gives the correct echo output, but doesn't allow me to execute the git tag command.

do_command git tag -a $NEW_VERSION -m "$INPUT_COMMENT"

and

do_command git tag -a $NEW_VERSION -m "\"$INPUT_COMMENT\""

Is there some way to make both echo and git command work in this call? Or do I need to parse in the do_command version?

Upvotes: 1

Views: 2422

Answers (1)

John Kugelman
John Kugelman

Reputation: 362107

Use "$@" with quotes to handle arguments with whitespace correctly. If you just write $@ then the git command won't work when $INPUT_COMMENT contains whitespace.

do_command() {
  if [[ $DRY_RUN ]]; then
    echo "$@"
  else
    "$@"
  fi
}

Usage:

do_command git tag -a $NEW_VERSION -m "$INPUT_COMMENT"

Upvotes: 6

Related Questions