cp command should ignore some files

Viewed 68596

Sometimes I need to perform following command

cp -rv demo demo_bkp

However I want to ignore all the files in directory .git . How do I achieve that? It takes a long time to copy .git files and I do not need those files.

5 Answers

Continuing on the rsync idea, if you have so many file patterns to ignore, you can use the --exclude-from=FILE option.

The --exclude-from=FILE option takes a file [FILE] that contains exclude patterns (one pattern per line) and excludes all the files matching the patterns.

So, say you want to copy a directory demo to demo_bkp, but you want to ignore files with the patterns - .env, .git, coverage, node_modules. You can create a file called .copyignore and add the patterns line by line to .copyignore:

.env
.git
coverage
node_modules

Then run:

rsync -rv --exclude-from=./.copyignore demo demo_bkp

That's it. demo would be copied into demo_bkp with all the files matching the patterns specified in .copyignore ignored.

Simple solution, possibly best runtime, conforming to OP (who wants to use cp):

touch /path/to/target/.git
cp -n -ax * /path/to/target/
rm /path/to/target/.git

This exploits the -n option of cp, which forces cp to not overwrite existing targets.

Drawback: Works with GNU cp. If you don't have GNU cp, then the cp operation might return an error code (1), which is annoying because then you can't tell if it was a real failure.

Related