在bash中传递参数给命令



我正试图将arg传递给clang-format:

arg="-style="{BreakBeforeBraces: Attach}""
clang-format -i $arg 'myfile.h'

,但得到以下错误:

No such file or directory
Invalid value for -style

但是,如果我简单地运行下面的命令:

clang-format -i -style="{BreakBeforeBraces: Attach}" 'myfile.h'

效果很好。

您可以简单地创建如下函数:

cfmt() {
clang-format -i "$@"
}

:

cfmt -style="{BreakBeforeBraces: Attach}" myfile.h

另一种安全的方法是将参数存储在shell数组中:

arg=('-i' '-style="{BreakBeforeBraces: Attach}"')
# use it as
clang-format "${arg[@]}" 'myfile.h'

当您直接运行命令时,Shell会删除双引号,因此不需要在变量value中引用它们。

你需要双引号变量,但是,保持它的内容一个字:

arg='-style={BreakBeforeBraces: Attach}'
clang-format -i "$arg" myfile.h

如果参数的数量不固定(可能包括0),则使用数组:

args=('-style={BreakBeforeBraces: Attach}')
clang-format -i "${args[@]}" myfile.h

最新更新