0

I'm using cmake to manage my c++ project on Ubuntu.

In the CMakeLists.txt, I want to add a custom target to execute some linux commands, here it is:

cmake_minimum_required(VERSION 3.9)
project(MyTest CXX)

add_custom_target(
    cov ALL
    )

add_custom_command(
    TARGET cov
    COMMAND touch xxx
    COMMAND echo -e '#!/bin/bash'>xxx
    )

In a word, I want to create a file named xxx and redirect the string #!/bin/bash into it. However, when I execute cmake . && make, I get an error: /bin/sh: 1: Syntax error: Unterminated quoted string. Obviously it is because the # is regarded as a comment by cmake so that this line becomes COMMAND echo -e ' .

I've also tried like this: COMMAND bash -c "echo -e '#!/bin/bash>'>xxx", but this gave me an empty xxx.

Yves
  • 11,597
  • 17
  • 83
  • 180

1 Answers1

1

Obviously it is because the # is regarded as a comment by cmake so that this line becomes COMMAND echo -e ' .

Yes. So the natural thing to do is to quote (for CMake) the text containing the # character ...

COMMAND echo -e "'#!/bin/bash'">xxx

..., or, my preference, to escape that character:

COMMAND echo -e '\#!/bin/bash'>xxx

I've also tried like this: COMMAND bash -c "echo -e '#!/bin/bash'>xxx", but this gave me an empty xxx.

Yes, because the double quotes (") are interpreted and removed by CMake. The result is equivalent to running this on the command line:

bash -c echo -e '#!/bin/bash'>xxx

. The command you're asking bash to run is just echo, with no arguments; the rest of the command line is interpreted by bash, not passed to echo.

Any way around, you need to appreciate and accommodate the effects of the two (or more) levels of interpretation of the command text, with their various independent requirements for escaping and quoting.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157