cp - do not overwrite in makefile

3

In the makefile for my project, I want it to copy a config file only if the file does not already exist in the destination folder. At the moment I am using:

cp -n

However, recently someone has told me that they are getting an "invalid option" error.

My question is: for a makefile, is there a more compatible method to achieve this than cp -n?

(Note: cp -u is not what I want, if the file already exists, it should never be replaced even if it is older than the source file.)

SlappyTheFish

Posted 2011-07-11T15:41:30.693

Reputation: 141

Answers

2

How about:

#!/bin/bash
if ! [ -e /path/to/foo ]
then
    cp foo /path/to/
fi

Even better, if this is e.g. a configuration file that might have new, useful options you could:

#!/bin/bash
if ! [ -e /path/to/foo ]
then
    cp foo /path/to/
else
    cp -f foo /path/to/foo.new
fi

so that they still have a copy they can refer to.

Pricey

Posted 2011-07-11T15:41:30.693

Reputation: 4 262

That's a great idea about the .new file, I'll use that - thanks! – SlappyTheFish – 2011-07-11T22:08:31.467

2

I think your commands from your Makefile are just going to be bash? If so, you can try using the bash if conditional that depends on whether the file exists:

if [ -f $FILE ];
then
   #echo "File $FILE exists"
else
   #echo "File $FILE does not exists"
   cp $SRC_FILE $FILE
fi

Bash code from here.

In the event that you discover the Makefile being run in environments where their contents are not evaluated against bash, then you could may be able to use rsync (should be installed on most unixy machines) for the copy operation. Though I just looked through the man page and didn't see a flag for copying only if dest doesn't exist - but I still sort of think that must be accommodated by rsync, just have to find the intended flag to use it.

James T Snell

Posted 2011-07-11T15:41:30.693

Reputation: 5 726

1

I had the same problem in a Makefile. Strange "cp -n" worked in the same shell. Would be interesting to know why?!

This is my solution, a bit shorten than if then else

test -e folder/requirements.txt || cp -p ../requirements.txt folder/requirements.txt

yvess

Posted 2011-07-11T15:41:30.693

Reputation: 111