Home > Mobile >  while loop in makefile not working but works from shell
while loop in makefile not working but works from shell

Time:06-06

I'm trying to write a makefile that will set up a new linux install for me. To start with, I want to describe all my packages in a text file and have them installed when I run make.

I am struggling with looping over the txt file in a makefile. However, the loop works from my shell.

makefile:

#!/bin/bash
SHELL=/bin/bash

install: reqs.txt
        echo working
        while read -r line; do
                echo "$line"
        done < <(grep -v "^--.*" reqs.txt)

reqs.txt:

--cli utils
nvim
tree
shellcheck

output when running make:

% make                                                                                                                           (master !?)
echo working
working
while read -r line; do
/bin/bash: -c: line 2: syntax error: unexpected end of file
make: *** [makefile:6: install] Error 2

output when running from cli:

% while read -r line; do                                                                                                         (master !?)
                echo "$line"
        done < <(grep -v "^--.*" reqs.txt)

nvim
tree
shellcheck

What am I doing wrong?

CodePudding user response:

Since make executes commands one line at a time, control structures that span multiple lines must be combined on a single line.

SHELL=/bin/bash

.PHONY: target
target:
    echo working
    while read -r line; do echo "$$line"; done < <(grep -v "^--.*" reqs.txt)

You can also use a backslash as shown below.

SHELL=/bin/bash

.PHONY: target
target:
    echo working
    while read -r line; do \
    echo "$$line"; \
    done < <(grep -v "^--.*" reqs.txt)

And note that the $ is replaced to $$. Otherwise, it will be considered a Make macro.

  • Related