How do I check if file exists in Makefile so I can delete it?

前端 未结 12 2054
心在旅途
心在旅途 2020-12-02 07:40

In the clean section of my Makefile I am trying to check if the file exists before deleting permanently. I use this code but I receive errors.

What\'s w

相关标签:
12条回答
  • 2020-12-02 07:57

    The second top answer mentions ifeq, however, it fails to mention that these must be on the same level as the name of the target, e.g., to download a file only if it doesn't currently exist, the following code could be used:

    download:
    ifeq (,$(wildcard ./glob.c))
        curl … -o glob.c
    endif
    
    # THIS DOES NOT WORK!
    download:
        ifeq (,$(wildcard ./glob.c))
            curl … -o glob.c
        endif
    
    0 讨论(0)
  • 2020-12-02 08:01

    I was trying:

    [ -f $(PROGRAM) ] && cp -f $(PROGRAM) $(INSTALLDIR)
    

    And the positive case worked but my ubuntu bash shell calls this TRUE and breaks on the copy:

    [ -f  ] && cp -f  /home/user/proto/../bin/
    cp: missing destination file operand after '/home/user/proto/../bin/'
    

    After getting this error, I google how to check if a file exists in make, and this is the answer...

    0 讨论(0)
  • 2020-12-02 08:03

    Or just put it on one line, as make likes it:

    if [ -a myApp ]; then rm myApp; fi;
    
    0 讨论(0)
  • 2020-12-02 08:10

    It's strange to see so many people using shell scripting for this. I was looking for a way to use native makefile syntax, because I'm writing this outside of any target. You can use the wildcard function to check if file exists:

     ifeq ($(UNAME),Darwin)
         SHELL := /opt/local/bin/bash
         OS_X  := true
     else ifneq (,$(wildcard /etc/redhat-release))
         OS_RHEL := true
     else
         OS_DEB  := true
         SHELL := /bin/bash
     endif 
    

    Update:

    I found a way which is really working for me:

    ifneq ("$(wildcard $(PATH_TO_FILE))","")
        FILE_EXISTS = 1
    else
        FILE_EXISTS = 0
    endif
    
    0 讨论(0)
  • 2020-12-02 08:10

    One line solution:

       [ -f ./myfile ] && echo exists
    

    One line solution with error action:

       [ -f ./myfile ] && echo exists || echo not exists
    

    Example used in my make clean directives:

    clean:
        @[ -f ./myfile ] && rm myfile || true
    

    And make clean always works without any error messages!

    0 讨论(0)
  • 2020-12-02 08:12
    FILE1 = /usr/bin/perl
    FILE2 = /nofile
    
    ifeq ($(shell test -e $(FILE1) && echo -n yes),yes)
        RESULT1=$(FILE1) exists.
    else
        RESULT1=$(FILE1) does not exist.
    endif
    
    ifeq ($(shell test -e $(FILE2) && echo -n yes),yes)
        RESULT2=$(FILE2) exists.
    else
        RESULT2=$(FILE2) does not exist.
    endif
    
    all:
        @echo $(RESULT1)
        @echo $(RESULT2)
    

    execution results:

    bash> make
    /usr/bin/perl exists.
    /nofile does not exist.
    
    0 讨论(0)
提交回复
热议问题