I need to execute a command with add_custom_command
a capture its stdout. The shell redirection to file >
does not work and add_custom_command
does not have any related options. How can I do it?
(Please note that I changed my answer after investigating the issue because of Florian's comment. More about the edit below)
The documentation of the execute_process
clearly states that it does not use intermediate shell, so redirection operators do not work there.
But it's not true for the add_custom_command
. Redirection should work there as expected. [EDIT] The reason sometimes it does not seem to work is some unfortunate combination of the CMake generator, the VERBATIM
specifier and the (missing) space between >
and the file name.
It turned out if you make sure there's a space between >
and the file name it works with in most cases, even with VERBATIM
:
add_custom_command(OUTPUT ${some-file}
COMMAND cmake --version > ${some-file}
VERBATIM # optional
)
A note on an alternative solution: previously I thought add_custom_command
, just like execute_process
doesn't use an intermediate shell so I suggested calling a CMake script which contains an execute_process
command which runs the actual command, redirecting its output with the OUTPUT_FILE
option.
If for some reason the solution above still fails for you, try the alternative solution using an ExecuteProcessWrapper.cmake
find_program(BASH bash HINTS /bin)
...
add_custom_command(
OUTPUT
${some-file}
COMMAND
${CMAKE_COMMAND} -E env ${BASH} -c "cmake --version > ${some-file} 2>&1"
VERBATIM
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With