从脚本调用 'git config' - 变量扩展

Calling 'git config' from a script - variable expansion

我正在使用以下命令配置 git 涂抹过滤器:

git config filter.ptc.clean "foo bar baz"
git config filter.ptc.smudge "foo bar baz"

有效。

现在,我想把它放到一个 'configure_filters.sh' 脚本中,我天真的方法是这样的:

#!/bin/bash
COMMAND="\"foo bar baz\""
git config filter.ptc.clean $COMMAND
git config filter.ptc.smudge $COMMAND

运行 'configure_filters.sh' 不起作用。 git 配置抱怨参数。

bash -x configure_filters.sh returns:

+ COMMAND='"foo bar baz"'
+ git config filter.ptc.smudge '"foo' bar 'baz"'
usage: git config [<options>]
...

COMMAND 变量似乎没有像我预期的那样展开。我该如何解决?

通过用双引号将您的变量括起来,它与您手动执行的完全一样。

#!/bin/bash
COMMAND="foo bar baz"
git config filter.ptc.clean "$COMMAND"
git config filter.ptc.smudge "$COMMAND"

如果您想将参数作为 "foo bar baz" 传递,并且 " 包含在值中,请使用以下内容:

#!/bin/bash
COMMAND="\"foo bar baz\""
git config filter.ptc.clean "$COMMAND"
git config filter.ptc.smudge "$COMMAND"

如果你只想传递 foo bar baz 而那些 " 在那里,因为你认为你从命令行 运行 他们需要他们那么我相信只是总结 "$COMMAND" 应该按如下方式工作:

#!/bin/bash
COMMAND="foo bar baz"
git config filter.ptc.clean "$COMMAND"
git config filter.ptc.smudge "$COMMAND"