Search code examples
makefilesh

Make file with if else condition inside the for loop


I am trying to loop using "for" inside the directory (dir) and building a go code and then checking with if dir name is equal to dir/task1 or dir/task2, is yes the zip the resource/ directory along with bootstrap else zip only bootstrap.

When I do make build, I see it is not going to else condition, please help

build:
    for directory in $$(find dir -mindepth 1 -maxdepth 1 -type d) ; \
        do env GOOS=linux go build -ldflags="-s -w" -o "bootstrap" $${directory}/main.go ; \
            if [ $${directory}='dir/task1' ] || [ $${directory}='dir/task2' ]; then \
                zip -r $${directory}.zip bootstrap resources/ ; \
            else \
                zip $${directory}.zip bootstrap ; \
            fi \
        done

Solution

  • That || in the if clause is a bashism — that is, it will fail for many Unix shells other than GNU Bash. Also, it worth explicitly passing -print to find as not all implementations of it default to printing when no explicit action was specified in the call.

    With these two fixed, the thing appears to work for me:

    $ cat Makefile 
    all:
        for directory in $$(find dir -mindepth 1 -maxdepth 1 -type d -print); do \
            echo $${directory}; \
            if [ $${directory} = 'dir/task1' -o $${directory} = 'dir/task2' ]; then \
                echo "\tif branch"; \
            else \
                echo "\telse branch"; \
            fi; \
        done
    
    $ mkdir -p dir/{task1,task2,task3,task4}
    $ make --trace all
    Makefile:2: target 'all' does not exist
    for directory in $(find dir -mindepth 1 -maxdepth 1 -type d -print); do \
        echo ${directory}; \
        if [ ${directory} = 'dir/task1' -o ${directory} = 'dir/task2' ]; then \
            echo "\tif branch"; \
        else \
            echo "\telse branch"; \
        fi; \
    done
    dir/task1
        if branch
    dir/task3
        else branch
    dir/task4
        else branch
    dir/task2
        if branch
    $