0

I used this post as a basis for how to pass arguments to a make target.

I would like to perform a string comparison on this command line arg, using this post as inspiration for doing string equality comparisons in a makefile.

Update using the suggested answer below:

%:
    @:

test:
    if [ '$(filter-out $@,$(MAKECMDGOALS))' = hi ]; \
        echo "WON"; \
    else \
        echo "LOST"; \
    fi

where I do 8 spaces instead of indents, nothing prints. When I do tabs instead of spaces, I get the following errors:

if [ 'hi' = hi ]; \
        echo "WON"; \
    else \
        echo "LOST"; \
    fi
/bin/sh: -c: line 0: syntax error near unexpected token `else'
/bin/sh: -c: line 0: `if [ 'hi' = hi ];     echo "WON"; else    echo "LOST"; fi'
make: *** [test] Error 2

Original attempt:

%:
        @:

test:
        ifeq ($(filter-out $@,$(MAKECMDGOALS)),hi)
                echo "WON"
        else
                echo "LOST"
        endif

However, when I run, make test hi, I get

arg="hi"
ifeq (hi,hi)
/bin/sh: -c: line 0: syntax error near unexpected token `hi,hi'
/bin/sh: -c: line 0: `ifeq (hi,hi)'
make: *** [test] Error 2 

What is the unexpected token ?

maddie
  • 1,854
  • 4
  • 30
  • 66

2 Answers2

2

ifeq is a make directive. By indenting it with a TAB, you have put it into the recipe, and all commands in the recipe are passed to the shell. The shell has no idea what an ifeq command is, and can't understand all the parens here, so you get these errors.

If you want to conditionalize on an automatic variable like $@, which are only available in the recipe, you have to write a shell conditional statement you can't use a make conditional statement:

test:
        if [ '$(filter-out $@,$(MAKECMDGOALS))' = hi ]; then \
            echo "WON"; \
        else \
            echo "LOST"; \
        fi
MadScientist
  • 92,819
  • 9
  • 109
  • 136
  • is there special spacing we need to do? When I run `make test hi`, nothing prints out – maddie Jul 21 '20 at 19:20
  • when I indent the `if/else` statement, I get `if [ 'hi' = hi ]; \ echo "WON"; \ else \ echo "LOST"; \ fi /bin/sh: -c: line 0: syntax error near unexpected token `else' /bin/sh: -c: line 0: `if [ 'hi' = hi ]; echo "WON"; else echo "LOST"; fi' make: *** [test] Error 2` – maddie Jul 21 '20 at 19:30
  • Sorry, forgot the _then_ – MadScientist Jul 21 '20 at 22:22
0

Leaving this answer as the one posted doesn't work as it is missing a then

test:
        if [ '$(filter-out $@,$(MAKECMDGOALS))' = hi ]; then \
            echo "WON"; \
        else \
            echo "LOST"; \
        fi

shell conditionals go if [] then ... else ... fi

maddie
  • 1,854
  • 4
  • 30
  • 66
  • 2
    Omitting the `then` was a small error that MadScientist has corrected; it would be appropriate to accept his answer. – Beta Jul 22 '20 at 03:31