4

I'm trying to do simple c++ class generator in makefile (depending on given name), but it's really annoying when i don't know bash, and how those things work.

class:
    @echo "Type class name: "; \
    read CLASS_NAME; \
    echo Creating class called $${CLASS_NAME}; \
    echo "Class $${CLASS_NAME} {
    int x;
    int y;
    };">./$${CLASS_NAME}.h  

How can I make the last echo work? I don't know how to echo multiple lines.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
grubazhuberto
  • 53
  • 1
  • 4
  • 1
    Out of curiosity -- did you actually set `SHELL` such that your makefile launches bash when it's running a shell command, or is it using `/bin/sh` (as it does by default)? – Charles Duffy Nov 29 '17 at 17:01
  • My bad, it should be shell as you said. – grubazhuberto Nov 29 '17 at 17:47
  • Duplicate of [Output multiline variable to a file with GNU Make](https://stackoverflow.com/questions/7281395/output-multiline-variable-to-a-file-with-gnu-make), I believe. The referenced question has an elegant solution. – Victor Sergienko Jun 02 '22 at 06:41

1 Answers1

2

The backslashes here are evaluated by make, not by the shell it invokes. (Similarly, make removes the newlines itself, instead of passing them to the shell).

The easiest thing to do here is to use a printf format string to insert your newlines rather than trying to make them literal:

class:
        @echo "Type class name: "; \
        read CLASS_NAME; \
        echo "Creating class called $${CLASS_NAME}"; \
        printf '%s\n' "Class $${CLASS_NAME} {" 'int x;' 'int y;' '};' >"./$${CLASS_NAME}.h"
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • Thanks mate, that works as i wanted! To be honest, i hadn't thought that i can use printf here. – grubazhuberto Nov 29 '17 at 17:41
  • `printf` is actually more portable than `echo`; see the APPLICATION USAGE section of the [POSIX standard for `echo`](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html), describing how and why to use `printf` instead. – Charles Duffy Nov 29 '17 at 17:46