0

I want to do something like this, wherein I define a variable whose expansion contains other variables, and those might need to be quoted strings.

CMAKE_BUILD_FLAGS=(-DCMAKE_VERBOSE_MAKEFILE=ON
                   -DCMAKE_CXX_FLAGS="-I/usr/local/include -L/usr/local/lib")

install_yaml_cpp() {
    (
        local version=0.6.2
            cd $DEPS_TMP_DIR && \
            rm -rf yaml-cpp-$version.tar.gz && \
            wget -N https://github.com/jbeder/yaml-cpp/archive/yaml-cpp-$version.tar.gz && \
            tar -v -xzf yaml-cpp-$version.tar.gz && \
            cd yaml-cpp-yaml-cpp-$version/ && \
            mkdir -p build && \
            cd build && \
            cmake ${CMAKE_BUILD_FLAGS[@]} -DYAML_CPP_BUILD_TOOLS=OFF -DYAML_CPP_BUILD_CONTRIB=OFF -DYAML_CPP_BUILD_TESTS=OFF .. && \
            make -j$(num_cpus) install
    )
}

What I need is that the shell interprets what I pass as

cmake -DCMAKE_CXX_FLAGS="-I/usr/local/include -L/usr/local/lib" …

i.e. exactly like I put in the array. However no matter how I quote and escape, It never works. Either I get only the part before the space, or it gets passed as

cmake '-DCMAKE_CXX_FLAGS="-I/usr/local/include -L/usr/local/lib"' …

or some such.

What is the correct way to pass nested variables with spaces and quotes to programs in a shell script?

oarfish
  • 4,116
  • 4
  • 37
  • 66
  • The idea is to single quote your 2nd argument - `CMAKE_BUILD_FLAGS=(-DCMAKE_VERBOSE_MAKEFILE=ON '-DCMAKE_CXX_FLAGS="-I/usr/local/include -L/usr/local/lib"')` an quote the array expansion - `"${CMAKE_BUILD_FLAGS[@]}"` – Inian Oct 01 '20 at 10:01
  • Unrelated, but it looks like you should be making a [tag:cmake] `CMakeLists.txt` file to include the external projects you need instead of a [tag:bash] script. – Ted Lyngmo Oct 01 '20 at 10:13
  • That would be an additional abstraction over what should be trivial source installs. this is only necessary in my case because OpenCV has a broken CMakeLists for my environment. – oarfish Oct 01 '20 at 12:47

0 Answers0