Monday, October 10, 2022

[SOLVED] Dynamically plug argument into shell command in Makefile routine

Issue

I am passing an argument to a Makefile routine, and am based on that determining which argument to pass to a subsequent shell command.

target:
    if [ "$(tensorflowgpu)" = "false" ]; then \
        conda env create -f temp-environment.yaml \
    else \
        conda env create -f environment.yaml \
    fi

I'm wondering if there is a way to plug the respectively apt .yaml file name directly into the conda create command without using the if else fi syntax. A ternary operator which does not assign its result to a variable seems to be unavailable in shell scripts.

If that really isn't feasible at all, I'm wondering if there's some other way to make this piece of code a little more maintainable and readable, apart from refactoring the conda create command to a function and passing the yaml file to that, maybe.

Disclaimer: I'm not too proficient with shell scripting.


Solution

You could do it like this:

target:
        [ "$(tensorflowgpu)" = "false" ] && prefix=temp- || prefix= ; \
        conda env create -f $${prefix}environment.yaml

I don't know if you like that any better.

Or, since you're using make variables here not shell variables, if you're willing to rely on GNU make, you could use constructed variable names:

YAMLFILE_false = temp-environment.yaml
YAMLFILE_base = environment.yaml

YAMLFILE = $(firstword $(YAMLFILE_$(tensorflowgpu)) $(YAMLFILE_base))

target:
        conda env create -f $(YAMLFILE)

Or you could use GNU make's if function; for example:

target:
        conda env create -f $(if $(filter false,$(tensorflowgpu)),temp-)environment.yaml

or you could put it in a variable to make it a little cleaner:

YAMLFILE = $(if $(filter false,$(tensorflowgpu)),temp-)environment.yaml

target:
        conda env create -f $(YAMLFILE)


Answered By - MadScientist
Answer Checked By - Gilberto Lyons (WPSolving Admin)