OUTPUT_VARIABLE of execute_process isn't initialized in install(CODE)

I’m experimenting with dynamic install scripts and encountered that OUTPUT_VARIABLE isn’t initialized after process finishes (this happens for built-in commands like cat, echo and probably others).
Here is the minimal CMakeLists.txt to verify behavior:

cmake_minimum_required(VERSION 3.16)
project(execute_process NONE)

execute_process(
    COMMAND "${CMAKE_COMMAND}" -E
        echo "Hello from echo!"
    OUTPUT_VARIABLE output
)
message(STATUS "${output}")

add_custom_target(none)

install(CODE
    "
    execute_process(
        COMMAND \"${CMAKE_COMMAND}\" -E
            echo \"Hello from echo in install CODE!\"
        OUTPUT_VARIABLE install_output
    )
    message(STATUS \"${install_output}\")
    message(STATUS \"install end!\")
    "
)

Here is the log:

...\CMakeTest\execute_process\build>cmake ..
-- Building for: Visual Studio 16 2019
-- Selecting Windows SDK version 10.0.19041.0 to target Windows 10.0.19043.
-- Hello from echo!

-- Configuring done
-- Generating done
-- Build files have been written to: .../CMakeTest/execute_process/build

...\CMakeTest\execute_process\build>cmake --install .
-- Install configuration: "Release"
--
-- install end!

...\CMakeTest\execute_process>cmake --version
cmake version 3.23.2
...

There is an empty line above -- install end!, though I expected the message Hello from echo in install CODE! would be shown there.
I’ve tested same script on Linux (with cmake 3.16.3), and it produces similar output - the expected message is missing.
Is this a bug or a feature?

I think the problem is that install_output is being expanded at configure time, not at install time.

Try this:

install(CODE
    "
    execute_process(
        COMMAND \"${CMAKE_COMMAND}\" -E
            echo \"Hello from echo in install CODE!\"
        OUTPUT_VARIABLE install_output
    )
    message(STATUS \"\$\{install_output\}\")
    message(STATUS \"install end!\")
    "
)

You might only need to escape the $, and not the brackets, experiment with it

1 Like

@benthevining , thanks a lot for the hint!
Escaping $ solves my problem!
Escaping the curly braces seems to be redundant (at least on Windows).

1 Like