如何将变量args =“ foo bar = \” baz qux \“”作为精确的* 2 *参数传递?

时间:2018-10-05 21:21:32

标签: bash arguments quoting variable-expansion

采用以下脚本:

#!/bin/bash

function print_args() {
    arg_index=1
    while [ $# -gt 0 ]; do
        echo "$arg_index: $1"
        arg_index=$(expr $arg_index + 1)
        shift
    done
    echo
}

echo "print_args foo bar=\"baz qux\""
echo "-----------------------------------------------"
print_args foo bar="baz qux"

args="foo bar=\"baz qux\""

echo "print_args \$args (args=\"foo bar=\\\"baz qux\\\"\")"
echo "-----------------------------------------------"
print_args $args

echo "print_args \"\$args\" (args=\"foo bar=\\\"baz qux\\\"\")"
echo "-----------------------------------------------"
print_args "$args"

它输出以下内容:

print_args foo bar="baz qux"
-----------------------------------------------
1: foo
2: bar=baz qux

print_args $args (args="foo bar=\"baz qux\"")
-----------------------------------------------
1: foo
2: bar="baz
3: qux"

print_args "$args" (args="foo bar=\"baz qux\"")
-----------------------------------------------
1: foo bar="baz qux"

我想要获得的输出如下:

-----------------------------------------------
1: foo
2: bar="baz qux"

这是print_args foo bar="baz quz"的结果。但是,我需要它是使用单个变量参数调用print_args的结果。我最终试图弄清楚如何在设置为运行

的shell脚本中将多个参数传递给CMake。
cmake ${cmake_flags} ../${target}

cmake_flags中的某些选项因为包含空格而需要被引用,但是我总体上希望CMake识别传递给它的多个不同选项,如果我引用cmake_flags则不会发生

1 个答案:

答案 0 :(得分:1)

改为使用数组语法,如下所示:

cmake_flags=( foo bar="baz qux" )

cmake "${cmake_flags[@]}"