When working on a server or managing files without a graphical interface, duplicating a single file is simple. However, copying an entire directory—including all the folders, scripts, and hidden files nested inside it—requires a slightly different approach. If you attempt to use the standard cp (copy) command on a folder, Ubuntu will instantly throw an error stating that the target is a directory and cannot be copied. To successfully copy a folder and its contents, you must tell the terminal to perform the action recursively.
Understanding the Recursive Flag (-r)
The standard cp command is designed only for individual files. To copy a directory, you must add the recursive flag (-r or -R). This flag instructs Linux to dive into the target folder, copy every file it finds, enter any sub-folders it finds, copy those files, and repeat the process until the entire folder tree has been duplicated perfectly.
How to Copy a Directory to a New Name
The most common scenario is duplicating a folder in your current location so you can safely edit files without breaking the originals.
The syntax is: cp -r [source_directory] [new_directory_name]
For example, if you have a folder named “website_data” and you want to create an exact backup copy called “website_data_backup”, you would type:
cp -r website_data website_data_backup
If you type ls after running the command, you will see both folders sitting side by side.
How to Copy a Directory to a Different Location
You can also use the cp -r command to copy a folder from your current location and place it entirely inside a different part of the file system.
The syntax is: cp -r [source_directory] [destination_path]
For example, to copy the “website_data” folder from your current directory and place it inside the /var/www/ directory:
sudo cp -r website_data /var/www/
Note: If you are copying files into a system directory (like /var/ or /etc/), you must use sudo to grant the command administrative privileges.
How to Copy the Contents Without the Parent Folder
Sometimes, you do not want to copy the folder itself; you only want to copy the contents inside it and dump them into another directory. To do this, you use the asterisk (*) wildcard character.
For example, to copy every file and sub-folder inside “website_data” and place them directly into /var/www/ (without creating a new “website_data” folder at the destination):
sudo cp -r website_data/* /var/www/
How to Preserve File Permissions (The -p flag)
When you copy a folder, the new copy will be owned by the user who ran the command, and the creation timestamps will change to the current time. If you are backing up system configuration files or web server directories, this can break permissions. To ensure the copied files retain their original ownership, permissions, and timestamps, add the preserve flag (-p).
sudo cp -rp /etc/nginx /home/user/nginx_backup