0

This is my current code

  .PHONY: setup-kind
  setup-kind:
      -eksctl get cluster integ-clus
      ([ $$? -eq "0" ] && echo "cluster exists") || echo "cluster does not exist"

This cluster does not exist so I expect "cluster does not exist" to be printed. The command(eksctl get cluster integ-clus) will fail because the cluster doesn't exist but the Makefile will keep running because i added a '-' to the start of the command(Ignore error)

The issue is that then the status of the command becomes a '0' because of my ignore addition and "cluster exists" will be printed as a result.

Does anyone have any suggestions on how I can approach this and get the code to execute the "cluster exists" block/logic?

committedandroider
  • 8,711
  • 14
  • 71
  • 126

1 Answers1

1

This is a common beginner error. Out of the box, every line in a make recipe executes in a separate subshell; the second line has no idea what happened in the first.

In this case, there is absolutely no reason to use two lines, anyway.

.PHONY: setup-kind
setup-kind:
    eksctl get cluster integ-clus \
    && echo "cluster exists" \
    || echo "cluster does not exist"

(The backslashes escape the newlines, so this is logically a single line.)

The result will be the exit code from either of the echos, so there is no need for a leading minus any longer.

Perhaps see also Why is testing ”$?” to see if a command succeeded or not, an anti-pattern?

By design, make will abort the current recipe if a command fails, so there is no well-defined way for a recipe to return a nonzero exit code and not abort the make or ignore the error result.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thank you for pointing me in the right direction. I found a cleaner solution(listing all the clusters and getting the size of that) and checking that against 0. – committedandroider May 13 '21 at 22:00
  • You're welcome (though there's another common antipattern lurking there, see [useless use of `wc`](http://www.iki.fi/era/unix/award.html#wc).) – tripleee May 14 '21 at 04:59