0

In a makefile, I want to use a shell command such as command1=[some program] [--flags], then use a condition to see whether or not the output contains a certain keyword using grep.

My code does not work:

var=$([command 1] | grep [keyword])
if [ -z ${var} ]; then \
[command 2, with variables in it]; \
[command 3, with variables in it]; \
fi

any idea why?

ntbd
  • 1

1 Answers1

1

What you show is not make syntax, it is shell syntax. So I will assume that it is part of a make recipe. Your problem is then that:

  1. Each line of a make recipes is passed to a different shell. So, you cannot pass shell variables from one line to the next. Use one single shell command list and line continuation (; \) to pass your entire recipe to one single shell.

  2. Make expands the recipes before passing them to the shell. Escape the make expansions by doubling the $ signs that you want to preserve ($${var}). Do the same for all shell variable expansions. You can also replace the $() command substitutions by the equivalent backtick notation `` instead of $$().

     target: prerequisite ...
         var=`[command 1] | grep [keyword]`; \
         if [ -z "$${var}" ]; then \
             [command 2, with variables in it]; \
             [command 3, with variables in it]; \
         fi
    
Renaud Pacalet
  • 25,260
  • 3
  • 34
  • 51