Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test whether a directory exists inside a makefile

Tags:

bash

makefile

In his answer @Grundlefleck explains how to check whether a directory exists or not. I tried some to use this inside a makefile as follow:

foo.bak: foo.bar     echo "foo"     if [ -d "~/Dropbox" ]; then         echo "Dir exists"     fi 

Running make foo.bak (given that foo.bar exists) yields the following error:

echo "foo" foo if [ -d "~/Dropbox" ]; then /bin/sh: -c: line 1: syntax error: unexpected end of file make: *** [foo.bak] Error 2 

The workaround I made was to have a standalone bash script where the test is implemented and I called the script from the makefile. This, however, sounds very cumbersome. Is there a nicer way to check whether a directory exists from within a makefile?

like image 260
Dror Avatar asked Dec 24 '13 16:12

Dror


People also ask

How do I know if a file is present in Makefile?

just do @rm -f myfile. Because of the "-f" flag, "rm" will exit with 0 regardless of whether the file exists or not. Or, -rm myfile the lead dash telling make to ignore any error.

Can Makefile target be a directory?

Yes, a Makefile can have a directory as target. Your problem could be that the cd doesn't do what you want: it does cd and the git clone is carried out in the original directory (the one you cd ed from, not the one you cd ed to). This is because for every command in the Makefile an extra shell is created.

How do you check if directory does not exist in Bash?

In order to check if a directory exists in Bash using shorter forms, specify the “-d” option in brackets and append the command that you want to run if it succeeds. [[ -d <directory> ]] && echo "This directory exists!" [ -d <directory> ] && echo "This directory exists!"


2 Answers

Make commands, if a shell command, must be in one line, or be on multiple lines using a backslash for line extension. So, this approach will work:

foo.bak: foo.bar     echo "foo"     if [ -d "~/Dropbox" ]; then echo "Dir exists"; fi 

Or

foo.bak: foo.bar     echo "foo"     if [ -d "~/Dropbox" ]; then \         echo "Dir exists"; \     fi 
like image 184
lurker Avatar answered Sep 25 '22 16:09

lurker


This approach functions with minimal echos:

.PHONY: all all: ifneq ($(wildcard ~/Dropbox/.*),)         @echo "Found ~/Dropbox." else         @echo "Did not find ~/Dropbox." endif 
like image 23
cforbish Avatar answered Sep 22 '22 16:09

cforbish