Linux commands: cp
By Flavio
Published · Updated
Tagged: CLI
Learn how the Linux cp command copies files from one place to another, and how the -r recursive option lets you copy entire folders and their contents.
You can copy a file using the cp command:
touch apple
cp apple another_apple
cp -i asks before overwriting an existing file.
To copy folders you need to add the -r option to recursively copy the whole folder contents. -R is the POSIX spelling. -r works on Linux and macOS:
mkdir fruits
cp -r fruits cars
Without -r, cp refuses a folder:
mkdir fruits
cp fruits cars
cp: -r not specified; omitting directory 'fruits'
Where the copy lands
If the last argument is an existing folder, the file is copied into it:
touch apple
mkdir fruits
cp apple fruits
You now have apple and fruits/apple. The original stays where it is.
If fruits does not exist, cp apple fruits creates a file named fruits. That is the usual surprise when you typo the folder name.
Overwriting
cp overwrites the destination file without asking. cp -i asks first. cp -n skips the copy when the destination exists.
cp does not keep timestamps or permissions by default. Use cp -p to keep them, or cp -a (archive) when you copy a folder and want a real duplicate.
To move or rename a file instead of copying it, use mv.
This command works on Linux, macOS, WSL, and anywhere you have a UNIX environment
Want me to talk about your product? You can sponsor this site.
Related posts about cli: