I can't figure out the right syntax to run a shell command in a post-build step in Cmake on Linux. I can make a simple echo work, but when I want to e.g. iterate over all files and echo those, I'm getting an error.
The following works:
add_custom_command(TARGET ${MY_LIBRARY_NAME}
POST_BUILD
COMMAND echo Hello world!
USES_TERMINAL)
This correctly prints Hello world!.
But now I would like to iterate over all .obj files and print those. I thought I should do:
add_custom_command(TARGET ${MY_LIBRARY_NAME}
POST_BUILD
COMMAND for file in *.obj; do echo @file ; done
VERBATIM
USES_TERMINAL)
But that gives the following error:
/bin/sh: 1: Syntax error: end of file unexpected
I've tried all sorts of combinations with quotation marks or starting with sh, but none of that seems to work. How can I do this correctly?
add_custom_command(and all the other CMake functions that execute aCOMMAND) don't run shell scripts, but only allow the execution of a single command. TheUSES_TERMINALdoesn't cause the command to be run in an actual terminal or allow the use of shell builtins like theforloop.From the documentation:
Or, alternatively, for very simple scripts you can do what @lojza suggested in the comment to your question and run the
bashcommand with the actual script content as an argument.Note that I deliberately used a CMake raw string literal here so that
${file}is not expanded as a CMake variable. You could also usebash -c "for file in *obj; do echo $file; done"with a regular string literal, in which case$filealso isn't expanded due to the lack of curly braces. Having copied and pasted bash code from other sources into CMake before I know how difficult it is to track down bugs caused by an unexpected expansions of CMake variables in such scripts, though, so I'd always recommend to use[[and]]unless you actually want to expand a CMake variable.However, for your concrete example of doing something with all files which match a pattern there is an even simpler alternative: Use the
findcommand instead of a bash loop: