How do I initialize a CMake variable with the result of a shell command

Is there a way to set a variable in a CMake script to the output of a shell command? Something like SET(FOO COMMAND "echo bar") would come to mind


You want the execute_process command.

In your case, on Windows:

execute_process(COMMAND CMD /c echo bar OUTPUT_VARIABLE FOO)

or on Linux, simply:

execute_process(COMMAND echo bar OUTPUT_VARIABLE FOO)


In this particular case, CMake offers a cross-platform solution. CMake can itself be used to run commands that can be used on all systems, one of which is echo. To do this, CMake should be passed the command line arg -E. For the full list of such commands, run cmake -E help

Inside a CMake script, the CMake executable is referred to by ${CMAKE_COMMAND}, so the script needs to do:

execute_process(COMMAND ${CMAKE_COMMAND} -E echo bar OUTPUT_VARIABLE FOO)