Matkrupp
Matkrupp

Reputation: 785

How can we avoid 'are the same file' warning message when using 'cp' in Linux?

I'm trying to copy certain files from one directory to another. Using this command

find "$HOME" -name '*.txt' -type f -print0 | xargs -0 cp -t $HOME/newdir

I get an warning message saying

cp: '/home/me/newdir/logfile.txt' and '/home/me/newdir/logfile.txt' are the same file

How can I avoid this warning message?

Upvotes: 28

Views: 57848

Answers (5)

Daniel Rijsketic
Daniel Rijsketic

Reputation: 11

Try using rsync instead of cp:

find "$HOME" -name "*.txt" -exec rsync {} "$HOME"/newdir \;

Upvotes: 1

user000001
user000001

Reputation: 33317

The problem is that you try to copy a file to itself. You can avoid it by excluding the destination directory from the results of the find command like this:

find "$HOME" -name '*.txt' -type f -not -path "$HOME/newdir/*" -print0 | xargs -0 cp -t "$HOME/newdir" 

Upvotes: 24

RandyMcMillan
RandyMcMillan

Reputation: 55

Install

It worked perfectly in a Makefile context with Docker:

copy:
    @echo ''
    bash -c 'install -v ./docker/shell                   .'
    bash -c 'install -v ./docker/docker-compose.yml      .'
    bash -c 'install -v ./docker/statoshi                .'
    bash -c 'install -v ./docker/gui                     .'
    bash -c 'install -v ./docker/$(DOCKERFILE)           .'
    bash -c 'install -v ./docker/$(DOCKERFILE_SLIM)      .'
    bash -c 'install -v ./docker/$(DOCKERFILE_GUI)       .'
    bash -c 'install -v ./docker/$(DOCKERFILE_EXTRACT)   .'
    @echo ''

build-shell: copy
    docker-compose build shell

Upvotes: 0

teknopaul
teknopaul

Reputation: 6772

Try using install instead. This replaces by removing the file first.

install -v target/release/dynnsd-client target/

Output:

removed 'target/dynnsd-client'
'target/release/dynnsd-client' -> 'target/dynnsd-client'

And then remove the source files.

Upvotes: 3

konsolebox
konsolebox

Reputation: 75478

Make it unique in the process. But this require sorting

find "$HOME" -name '*.txt' -type f -print0 | sort -zu | xargs -0 cp -t "$HOME/newdir"

Or if it's not about the generated files, try to use the -u option of cp.

find "$HOME" -name '*.txt' -type f -print0 | xargs -0 cp -ut "$HOME/newdir"
-u   copy only when the SOURCE file is newer than the destination file or when
     the destination file is missing

Upvotes: 1

Related Questions