cp command in linux Many new users of Linux take the time to learn the cp command, but they often make mistakes.
People often have no idea that one incorrect usage of the cp command will overwrite files that are important to their system or will result in the loss of entire projects .
Users who use the cp command without understanding the implications find out about the problems caused by a careless command too late.
With the knowledge you will gain from this 3000+ word article, you can avoid making mistakes when copying files and folders. You will also learn how to:
- Copy an individual and multiple files/directory-tree structure
- Avoid overwriting an existing file
- Preserve the file permission/owner
- Use the
cpcommand in real-life situations that relate to your work projects and systems
When you complete this guide, you will have the skills to confidently use the cp command in a variety of environments without the fear of making a mistake that could result in the loss of important data.
Table of Contents
- Basics and overview
- Basic syntax and single-file copy
- Copy multiple files to a directory
- Copy directories recursively with -r / -R
- Interactive and safe copying
- Preserve attributes and permissions
- Verbose output and troubleshooting
- Using wildcards and patterns
- Real project and backup use cases
- Best practices to avoid data loss
Basics and overview
The cp command provides an easy way to duplicate data (files or folders) in Linux.
When managing configuration files for servers and software customization, the cp command is one of the best tools for working with backup systems and creating project folders.
- Provides a way to quickly duplicate information without having to change the location of the data.
- Creates a way to manually back up files before making changes to production systems.
- Can be specified with a number of different options related to how to handle permissions and metadata.
The cp command works on all distributions of Linux; therefore, it is a basic skill that every Linux user should understand.
The cp command can be used in automation scripts to deploy applications or update systems.
At its most basic level, when using the cp command in Linux there are at least 2 parameters: a source (what you want to copy) and a destination (the location of where to copy the source).
If the destination is a file and it already exists, the cp command will overwrite the existing file, by default.
Knowing the cp commandās “silent overwrite functionality” is important to ensure safety while copying files in Linux.
Learning this command will allow you to evolve from a user who only wishes that a copy was successful, to an administrator who verifies and monitors each and every copy operation using the cp command in Linux.
Whether you are a developer duplicating a .env.example or a sysadmin backing up /etc/ssh/sshd_config, the cp command in Linux remains the most reliable tool available on the Terminal.
Basic syntax and single-file copy
The most common use case for the cp command linux is duplicating a single file within the same directory or to a new path. This simple operation is the foundation for all other advanced copying tasks.
- Copy a file to a new name using
cp file1.txt file2.txt. - Copy a file into a different directory with
cp document.pdf ~/Documents/. - Quickly create a backup with a date suffix like
cp script.sh script.sh.bak. - Rename and move a file simultaneously by specifying a full path and new filename.
- Verify that the original file remains untouched while the new copy is created.
To copy a file named notes.txt to a backup called notes_old.txt, simply run cp notes.txt notes_old.txt. This creates an exact replica of the content in your current working directory.
When copying to a different folder, the cp command in linux doesn’t require you to type the name again. Running cp config.yaml /etc/myapp/ will place a copy named config.yaml inside that destination folder automatically.
If you want to copy a file and give it a new name in a new location, you can do that too. For example, cp report.txt ~/backups/report_january.txt performs both the move and the rename in a single execution of the cp command in linux.
Copy multiple files to a directory
Often the efficiency of Linux means doing as much as possible with as little typing as possible. The linux cp command lets you move up to dozens of files into a target directory from just one command line.
Simultaneously copy several specified files with the command: cp file1 file2 file3 target_dir/.
Also, organise mixed types of files into specific project folders at once.
- Using batch processing for file copying reduces the chance of errors occurring through manual operations.
- With this capability, one can speed up the process of preparing files for web server deployment or application release.
- Also, you can save yourself time by using it instead of repeatedly invoking command to copy files one at a time.
When you copy multiple items, the final argument you enter must always be a directory. For instance, if you run cp a.txt b.txt c.txt, linux will return an error; as it has nowhere set up to put those files.
An example is: let’s say you are a web developer; you might run cp index.html style.css script.js /var/www/html/; this puts all of your frontend files into the root of your web server all at once and in a clean manner.
The use of this batch ability along with tab completion makes the cp command an extremely useful tool because you can start typing in the filename, press tab to finish typing the filename, and then add the name of the folder you want to use.
Copy directories recursively with -r / -R
When using “cp” in Linux, there is a default error and warning to inform developers that your command failed because of an omitted directory.
To successfully copy folders and everything inside a folder in Linux, you will need to add the “recursive” flag ā this is a basic command that all junior administrators should know.
To copy the source folder and all sub-directory folders (all files and sub-folders), use:
cp -r ~/source_dir/ ~/destination_dir/
- To duplicate entire project hierarchy structure while maintaining internal file organization.
- To help new developers avoid missing and common errors such as “omitting direcotory,” this process allows you to create a mirror image of a complex configuration tree for testing or backup purposes.
Alternatively, this command supports the use of the -R option instead of the -r option, which has the same recursive functions.
If you run a copy command like “cp my_project/ backup/” without any flags in Linux OS, an error message will show, “cp: -r not specified; omitting directory.”
The warning message and error that displays is intended to protect and avoid causing an error where you accidentally copied a massive amount of data.
The fix would be to issue the command again, but use the flag edition to indicate that you want the folder and everything inside it:
cp -r my_project/ backup/ will now tell Linux to go inside my_project and take out and copy all files and subdirectories, re-establishing the same structure in the new backup directory.
The recursive ability of the “cp” command is important for duplicate ftps based repositories, large media libraries, etc. and it allows to maintain the same hierarchical structure as the source folder.
Benefits of cp command in linux: Interactive and safe copying
One of the main issues when using the cp command in Linux is that it enables users to accidentally overwrite files without first confirming whether or not to do so.
Thankfully, there are a few ways around this issue by enabling certain options when using cp. By enabling interactive mode with cp -i, you get a confirmation prompt if the destination location already has an existing file that is being copied over to it.
For instance, if you typed in cp -i config.php config.php.new and the cp command determined that a file named config.php.new already existed at the destination address, it would ask you to confirm whether or not you want to overwrite the existing file with the new one ā allowing you to type in y (for yes) or n (for no).
There is also another option called cp -n which stands for “no-clobber.” This option prevents you from ever overwriting a file that already exists at a destination.
If you want to copy a large number of files, but only want to copy files that do not exist at the destination, using cp -n is the ideal way to do this. It will simply skip any files that already exist at the destination address.
Many senior administrators choose to create an alias of the cp command in their .bashrc file so that when they use the command, it defaults to acting at cp -i.
This gives them an added layer of protection and greatly reduces the likelihood of typos occurring in these high-pressure situations.
Benefits of cp command in linux: Preserve attributes and permissions
In Linux, most times when you copy a file it appears as though you are the new owner.
For system backups though you need to use the cp command with the correct switches to retain the Original owner’s information, as well as retain the original file timestamps.
To preserve both the original owner’s information and timestamps you would use the cp -p option.
If you wanted to preserve everything then you would use the cp -a option which includes symbolic links.
When moving system service-related files it’s important to be certain that all permissions remain intact and valid after the move.
You are also responsible for documenting both created and modified dates within the audit logs.
In addition, if you’re copying a directory from /var/www to a backup device you will need to use the cp -a /var/www /backup/ option in order to make certain that the user account associated with the web server (in many situations www-data) maintains ownership of the copies placed in the backup.
If you do not use either switch then the owner of the copied files may be you, your current user, and as a result any application may fail because it no longer has permission to read its own configuration file.
The ultimate switch is the -a (Archive) flag. This combines recursive copying, permissions preservation and link checks into one switch and is the most common use for professionals backing up their systems using cp command in linux.
Benefits of cp command in linux: Verbose output and troubleshooting
Verbose mode (using cp with the ‘-v‘ option) in Linux allows you to see every file that is moved, which makes it valuable for solving problems.
Here are the benefits of using verbose mode:
- Use
cp -vto determine all files being copied. - If a
cpoperation lasts longer than expected, you can debug it and see if it has stopped copying or to what point it was working. - Before running a batch copy script, you can make sure that wildcards are selecting the intended files.
- By using ‘
cp -rv src/ dest/‘, you can create a log of the entire process using ‘cp -rv src/ dest/ > log.txt‘. - Use
cp -rvto see which file caused an error during a large batch copy operation.
When you run ‘cp -rv src/ dest/‘, you will see a line printed to the terminal stating ‘src/photo.jpg‘ -> ‘dest/photo.jpg‘. This helps assure you that the cp command has done as you expected it to do.
Verbose output is useful for junior administrators who may be unclear about the workings of the cp command or how it creates the folder structure for each file.
If your copy operation fails because of a permission error and you run cp -rv src/ dest/ with sudo, you can see which sub-folder is blocking you from copying the files due to the permission issue.
Using wildcards and patterns
Typing the names of each file manually can be impractical when working with large datasets.
The Linux cp command is capable of working very well with shell wildcards which allow you to select the exact files to copy based on their filename.
You can use cp to copy all files of a specific extension using the wildcard asterisk by entering cp *.jpg ~/Photos/.
You can also copy files whose names begin with specific prefixes, such as: cp backup_2024* /external_drive/.
If you want to copy a specific range of versioned files, you can use square brackets within your wildcard: cp v[1-3].doc archive/.
If you want to copy several files while excluding certain files, you can cleverly use pattern matching.
By using directory flags in combination with any pattern matches, you can precisely manage your data.
When using the wildcard asterisk (*) with cp, it will match anything that has the wildcard.
Therefore, if you use the cp command in Linux and enter cp project_*.py ~/scripts/, you will copy project_v1.py, project_final.py, and project_test.py all at once.
You must exercise caution when using the cp command with wildcards. Always check your current working directory first (using ls) to ensure that you’re not copying more files than you intended.
A helpful tip for ensuring safety when using wildcards with cp is to use ls first to display all of the “.txt” files.
If the output displays the exact files that you want, you can press the up arrow key to bring up the command line a second time and change ls to cp and execute your cp command safely.
Real project and backup use cases
Theoretical knowledge is only one aspect of learning Linux; to become a fully qualified Linux Professional, you have to have hands-on experience using the cp command in the operating system and apply it in real-world situations to develop your skill set.
The initial setup of your project’s environment variables can be done using the command cp .env.example .env.
Prior to editing your website’s “live” version, you will often use the command cp -p index.html index.html.old to make a “backup” of your current index file.
Log rotation can be done with the command cp /var/log/syslog /backup/logs/syslog_$(date +%F), which allows you to append today’s date to the log filename.
This avoids confusion when restoring logs and makes it easier to maintain an accurate chronological record of your log files without having to rename them manually.
When managing documents, using the cp command is superior to using a graphical user interface (GUI) because it is faster.
Scripting the copying of a template file into ten different folders with the cp command takes just a few seconds compared to minutes spent using the mouse to perform the same task with a GUI.
Benefits of cp command in linux: Best practices to avoid data loss
The cp command in Linux is important for more than simply being familiar with the tools available to you.
More importantly, having a disciplined method of computing safely and correctly is critical to the longevity of your career. By consistently adhering to these rules, you can expect to save your career from certain disaster at least once.
- Always use the
-iflag when copying files to a directory that already contains files. - Use the
-nand/or-vflags when testing a recursive copy to verify your results before undertaking a significant amount of data transfer. - Always specify the
-pflag when copying sensitive files (such as SSH keys). - When writing a script, make sure to specify absolute path names (with the Leading ‘/’) to avoid unintentional copying to the wrong directory.
- Always check that the destination disk has enough capacity prior to copying a large folder using the
df -hcommand.
An example of this is copying a folder containing thousands of files onto a partition that is nearly full. The cp command in Linux can fill your hard drive to capacity before it finishes, resulting in a hung server.
Another important rule is always double-checking your source and destination one last time.
By running the pwd command immediately before running the cp command, you can make sure you are currently located at the directory where you think you are, and thus will not copy the wrong config.json file.
Finally, you must remember that cp is designed for creating copies of files, and if you wish to move a file (and delete the original) you should be using the mv command. Knowing when to use each command is an essential component of understanding the Linux operating system.
What Are the cp command in linux? Your Questions Answered
Q: What is cp command in linux used for?
It copies files and directories from one location to another. You can use options to copy multiple files, directories, preserve attributes, and avoid accidental overwrites.
Q: How do I copy a directory in Linux?
You must use the recursive flag. The cp command in linux for this is cp -r source_directory destination_directory.
Q: How can I avoid overwriting files with cp command in linux?
Use the -i flag for interactive mode, which asks for permission, or the -n flag, which prevents overwriting entirely.
Q: What does the -a flag do in cp command in linux?
The -a flag stands for “archive.” It copies directories recursively while preserving all permissions, ownerships, and symbolic links.
Q: How do I copy multiple files at once?
List all files followed by the destination directory: cp file1.txt file2.txt /path/to/destination/ using the cp command in linux.
Q: Can I rename a file while copying it?
Yes. If you specify a new name as the destination, like cp old.txt new.txt, the cp command in linux creates a renamed copy.
Q: How do I see what is being copied?
Use the verbose flag -v. The cp command in linux will print the status of every file it processes to the terminal.
Q: What is the difference between -r and -R in cp command in linux?
In modern Linux versions, they are identical and both stand for “recursive” copying of directories and their contents.
Q: How do I preserve file timestamps?
Use the -p flag. The cp command in linux will ensure the “Last Modified” time remains the same as the original file.
Q: How do I copy all files with a specific extension?
Use a wildcard: cp *.jpg /destination/folder/. This tells the cp command in linux to grab every JPEG file in the folder.
Q: Why do I get “omitting directory” error?
This happens because you tried to copy a folder without the -r flag. The cp command in linux requires recursion for folders.
Q: Can I copy files to a remote server with cp command in linux?
No, cp is for local files. For remote copying, you should use scp or rsync.
Q: How do I create a backup of every file I overwrite?
Use cp --backup source destination. The cp command in linux will create a copy and append a tilde (~) to the old version.
Q: What happens if the destination directory doesn’t exist?
The cp command in linux will treat the destination as a new filename rather than a folder, which might not be what you want.
Q: How do I copy a hidden file in Linux?
Hidden files start with a dot. Use cp .bashrc ~/backups/ to copy specific hidden files with the cp command in linux.
Q: Can I copy symbolic links as links instead of files?
Yes, use the -d flag or the -a flag. This prevents the cp command in linux from following the link and copying the data it points to.
Q: How do I force an overwrite without being asked?
Usually, cp does this by default. However, if you have an alias set, use \cp or -f to force the cp command in linux.
Q: How do I copy a file but only if the source is newer?
Use the -u (update) flag. The cp command in linux will only copy if the source file is newer than the destination file.
Q: How do I copy files while ignoring errors?
While not recommended, you can use cp in a script with 2>/dev/null to hide error messages from the cp command in linux.
Q: Does cp command in linux use much CPU?
No, it is very lightweight. Its performance is limited by your disk speed (I/O) rather than your CPU power.