0

I create a function rendering input text(argument)

#Color renderning
define GPrint 
    kColorRed := "\x1b[0;31m"
    kColorGreen := "\x1b[0;32m"
    kColorEnd := "\x1b[0m"
    @echo -e "${kColorGreen}${1}${kColorEnd}"
endef

when I call this funtion

.PHONY : create_odir
create_odir:
    $(call GPrint "create output dir")
    mkdir ./output_dir

I got this error message

kColorRed := "\x1b[0;31m"
/bin/sh: line 1: kColorRed: command not found
make: *** [../src/sw/makefile:51: create_odir] Error 127

How do I solved it?

curlywei
  • 682
  • 10
  • 18
  • Maybe this: https://stackoverflow.com/questions/2268104/command-not-found-error-in-bash-variable-assignment/2268117#2268117 ? – Vroomfondel May 12 '21 at 14:11
  • @curleywei does the solution I provided works for you – Altaf May 12 '21 at 16:02
  • Hi @Vroomfondel: I've applied your suggestion, then `kColorRed` is found. But output text does not change color. – curlywei May 13 '21 at 03:04
  • This is because `make` invokes a separate shell process for each line in a recipe, thereby forgetting everything from previous lines. I completely forgot to mention this in my first comment, sorry. You can either write the whole recipe in one line, putting a `;`as command separator or the `;` and a `\ ` at the end of each line inside the `define` to mark it to be passed as one line to the shell processor by `make`. – Vroomfondel May 13 '21 at 12:24

1 Answers1

1

Please see below code which will help you fix this issue.
Method 1: Using global variables

# Regular Colors
kColorRed ='\e[0;31m'          # Red
kColorGreen ='\e[0;32m'        # Green
kColorEnd='\e[0m'              # Text Reset

# Color renderning
define GPrint 
    echo -e ${kColorRed}$(1)${kColorEnd}
    echo -e ${kColorGreen}$(1)${kColorEnd}
endef

create_odir:
    $(call GPrint ,"create output dir")

Output :
enter image description here

Method 2: If you want to use local variables inside the function.

# Color renderning
define GPrint 
    $(eval kColorRed := '\e[0;31m')
    $(eval kColorGreen := '\e[0;32m')
    $(eval kColorEnd := '\e[0m')
    echo -e $(kColorRed)$(1)$(kColorEnd)
    echo -e $(kColorGreen)$(1)$(kColorEnd)
endef

create_odir:
    $(call GPrint ,"create output dir")
Altaf
  • 2,838
  • 1
  • 16
  • 8
  • Seems can't use local variable in `define ... endef` Has a solution that we can use local variable within `define ... endef` ? – curlywei May 13 '21 at 02:35
  • @curlywei I have added example using local variables now. It will also give you the same output – Altaf May 13 '21 at 08:15
  • @curlywei does the solution I provided works for you. – Altaf May 13 '21 at 08:21
  • HI @Altaf: Good! Thanks! I recommend add `@` for each command inside `GPrint`, otherwise redundant command could be displayed on the terminal, such as `echo -e`. Could fix your code in Method 2? Thanks :) – curlywei May 13 '21 at 08:53
  • 1
    @curlywei, wlecome:-). you can also use.SILENT to suppress commands – Altaf May 13 '21 at 10:57