简体   繁体   English

bash:扩展函数参数

[英]bash: expanding function arguments

I have an issue with a bash function for a shell script i'm writing. 我正在编写的Shell脚本的bash函数存在问题。 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. 功能很简单,如果设置了DRY_RUN标志,我们只打印该方法,否则将执行它。 This works well for most commands except git tag command that I have tried different versions of like: 对于大多数命令,除了我尝试过不同版本的git tag命令,该命令都适用:

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

That actually executes the tag command, but give the comment $INPUT_COMMENT 实际上执行了tag命令,但给出了注释$ 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. 我尝试了其他2个版本,这些版本提供了正确的回声输出,但不允许我执行git tag命令。

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? 有什么方法可以使echo和git命令在此调用中起作用? Or do I need to parse in the do_command version? 还是我需要解析do_command版本?

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. 如果您只写$@则当$INPUT_COMMENT包含空格时, git命令将不起作用。

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

Usage: 用法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM