将参数传递给 bash 中的命令
pass arguments to a command in 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'
它工作得很好。
Shell 直接 运行 命令时删除双引号,因此无需在变量值中引用它们。
不过,您需要对变量加双引号,以使其内容保持一个词:
arg='-style={BreakBeforeBraces: Attach}'
clang-format -i "$arg" myfile.h
如果参数个数不固定(包括可能的0个),使用数组:
args=('-style={BreakBeforeBraces: Attach}')
clang-format -i "${args[@]}" 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'
我正在尝试将 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'
它工作得很好。
Shell 直接 运行 命令时删除双引号,因此无需在变量值中引用它们。
不过,您需要对变量加双引号,以使其内容保持一个词:
arg='-style={BreakBeforeBraces: Attach}'
clang-format -i "$arg" myfile.h
如果参数个数不固定(包括可能的0个),使用数组:
args=('-style={BreakBeforeBraces: Attach}')
clang-format -i "${args[@]}" 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'