- Linux – How To Copy a Folder [ Command Line Option ]
- How To Copy a Folder with cp Command
- Linux cp command examples
- More examples of cp command to copy folders on Linux
- Use Linux rsync Command to copy a folder
- Conclusion
- How to Copy files and folders in Linux
- What is cp command?
- Common syntax for cp command:
- Common options for cp command:
- 1) Copying files with cp command
- 2) Copying files with a different name
- 3) Copying multiple files in Linux
- 4) How to copy directories recursively
- 5) Copying multiple directories recursively
- 6) Copying specific format files in Linux
- 7) Copying all files at once in Linux
- 8) How to copy hidden files (‘.’ dot files) in Linux
- 9) Backup the file with cp command
- 10) Copying files with attributes
- 11) How to avoid file overwriting with cp command?
- 12) Prompting confirmation with cp command
- 13) Copying link files in Linux
- Conclusion:
- How to Use the Command-line to Copy files and folders in Ubuntu Linux?
- Related Posts
- 13 thoughts on “How to Use the Command-line to Copy files and folders in Ubuntu Linux?”
Linux – How To Copy a Folder [ Command Line Option ]
How To Copy a Folder with cp Command
The cp command is a Linux command for copying files and directories. The syntax is as follows:
Linux cp command examples
In this example copy /home/vivek/letters/ folder and all its files to /usb/backup/ directory:
cp -avr /home/vivek/letters /usb/backup
Where,
- -a : Preserve the specified attributes such as directory an file mode, ownership, timestamps, if possible additional attributes: context, links, xattr, all.
- -v : Verbose output.
- -r : Copy directories recursively.
More examples of cp command to copy folders on Linux
Copy a folder called /tmp/conf/ to /tmp/backup/:
$ cp -avr /tmp/conf/ /tmp/backup/
Sample outputs:
Fig.01: cp command in action
Use Linux rsync Command to copy a folder
You can also use rsync command which is a fast and extraordinarily versatile file copying tool. It can make copies across the network. The syntax is as follows for the rsync command
To backup my home directory, which consists of large files and mail folders to /media/backup, enter:
$ rsync -avz /home/vivek /media/backup
I can copy a folder to remote machine called server1.cyberciti.biz as follows:
$ rsync -avz /home/vivek/ server1.cyberciti.biz:/home/backups/vivek/
Where,
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
- -a : Archive mode i.e. copy a folder with all its permission and other information including recursive copy.
- -v : Verbose mode.
- -z : With this option, rsync compresses the file data as it is sent to the destination machine, which reduces the amount of data being transmitted something that is useful over a slow connection.
Fig.02: rsync command in action
Conclusion
You just learned how to copy a folder on a Linux like operating system using the cp command and rsync command. In conclusion, use rsync for a network folder transfer and cp for a local disk transfer.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How to Copy files and folders in Linux
Being a Linux user, copying files and directories is one of the most common tasks.
Linux users don’t spend a day without using the cp (copy) command according to my personal experience. cp command is used to copy a single file or group of files or directory.
To perform the copy operation, you must have at least read permission in the source file and write permission in the target directory.
In this article, we will explain how to use the cp command.
To perform remote file copy, use the commands such as rsync command or scp command or pscp command.
What is cp command?
‘cp’ command is one of the basic and most widely used Linux commands for copying files and directories from one location to another.
When copying files from source to destination, the source file remains the same and the target file may have the same or different name.
Common syntax for cp command:
Common options for cp command:
Options | Description |
---|---|
-v | Verbose mode (Show progress) |
-r/R | Copy directories recursively |
-n | Don’t overwrite an existing file |
-d | Copy a link file |
-i | Prompt before overwrite |
-p | Preserve the specified attributes |
-b | Make a backup of each existing destination file |
To demonstrate file copy operation in detail, we will be performing a copy operation between user1 and user2 .
1) Copying files with cp command
Use the following command to copy a file from one location to another.
In the following example, we will copy the source file “/home/user1/cp-demo.txt” to the target directory “/home/user2” with the same name:
You can check whether the specific file is copied to the target directory using the ls command as shown below:
2) Copying files with a different name
Use the following command to copy a file from one place to another with a different name. You need to give a new name to the target file.
In the following example, we will copy a file named “/home/user1/cp-demo.txt” to the target directory with a new name “/home/user2/cp-demo11.txt” :
Use the ls command to verify this:
3) Copying multiple files in Linux
The following cp command copies multiple files from one location to another.
In this example, we will copy the following three files named “cp-demo.txt, cp-demo-1.txt and cp-demo-9.txt” to the target.
No additional option is required to copy multiple files, and the file name(s) must be separated with a space as shown below:
Use the ls command to verify the copied files. You should see them in the target directory as shown below:
4) How to copy directories recursively
To copy a directory recursively from one location to another, use the -r/R option with the cp command. It copies everything, including all its files and subdirectories.
In the following example, we will copy the ‘/home/user1/cp-demo-folder’ directory to ‘/home/user2/’ and the target directory name will remain the same:
Use the ls command to verify the outcome. You should see them in the target directory as shown below:
5) Copying multiple directories recursively
Use the following command to copy multiple directories at once. In the following example, we will copy the public_html & public_ftp folders to the target directory named /home/2daygeek/cp-test.
Output can be verified using the ls command:
6) Copying specific format files in Linux
Sometimes you may have to copy files with a specific extension for a certain purpose. If so, you should use the cp command with the «wildcard (*)» option and the file extension name.
In the following example, we will copy all the files containing the *.sh extension from the source to the target directory. Similarly, you can copy any file extensions such as .jpg, .png, .txt, .php, and .html.
This can be verified using the ls command:
7) Copying all files at once in Linux
To copy all the files except the directory from one location to another, use the following cp command with wildcard (*) option.
cp command excludes directories by default, and the -r option must be added to copy them.
In this example, we will copy all the files from ‘/home/user1/’ to ‘/home/user2′ :
Verify the output using the ls command as shown below:
8) How to copy hidden files (‘.’ dot files) in Linux
By default, the cp command does not copy “dot (.)” or ‘hidden’ files in Linux.
Use the following command to copy all types of files, including link files (soft link or hard link), folders and hidden or dot files from source to destination.
This example is very useful to copy user’s home directory which has several hidden files:
You can verify this by using the ls command with the “-a” option:
9) Backup the file with cp command
cp command allows you to backup the file if the same file name exists in the target directory using the —backup option.
In this example, we will copy the /home/user1/passwd-up.sh file to the target directory /home/user2/.
It will backup the “passwd-up.sh” file in the target directory during the copy operation, if you say “yes” when you see the message below:
It adds the “Tilde (
)” symbol at the end of the old file, the same can be verified in the following output.
10) Copying files with attributes
By default, Linux replaces file attributes such as username, group name, date and time when copying files from a user, and does not carry the original file attributes.
To preserve the original attributes of the files, use the -p option with the cp command.
Upon querying we can see that the file “service-1.sh” has retained its original attributes as shown below:
11) How to avoid file overwriting with cp command?
When copying a file, use the -n option with the cp command to avoid overwriting an existing file.
It will only copy the source file, if the target directory does not have a file with the same name. If a duplicate file exists in the target, then the command will run, but won’t make any changes:
Upon querying using the ls command, it can be seen that no action is taken against the file because it still has the old attributes, which can be seen in the above example (refer section 10):
12) Prompting confirmation with cp command
Use the -i option with the cp command to prompt for confirmation before overwriting the file, in case the file exists in the target location.
The following example prompts for confirmation when copying the “cp-demo-9.txt” file because the file already exists in the target directory:
13) Copying link files in Linux
By default, the cp command excludes link files while performing the copy operation. Use the -d option with the cp command to copy the link files as shown below:
It has been successfully copied, and the soft link file can be found in the below output:
Conclusion:
In this tutorial, we have demonstrated 13 methods that are widely used by the Linux administrators in their daily operations. If you would like to explore other options, please visit the man page of the cp command by using the following command:
Источник
How to Use the Command-line to Copy files and folders in Ubuntu Linux?
Learning how to use the command-line for copying files and folders (or backing up etc) in GNU/Linux sometimes can come in real handy. Because the GNU/Linux operating system is fundamentally designed and run through the command-line interface, thus even if your desktop fails to load, there’s a good chance that you should still be able to use the command-line to login to your user account and backup your data (supposing that you don’t have an Ubuntu Live CD/USB flash drive around :)).
So if your desktop fails to load at the login screen and doesn’t takes you to a ‘login shell’ (a ‘Terminal’ in full-screen, without a desktop), then you can open one manually by pressing the ‘Alt’ + ‘Ctrl’ + ‘F1’ keys on your keyboard and it should open a new login shell for you.
Then you can use your existing user name and password to login to a non graphical interface and begin copying files.
You can also use these commands while the desktop is working, by using ‘Terminal’ just as you’d use it to install software using the ‘apt-get install …’ as well. For this example I’m using Ubuntu 12.04 Precise Pangolin and running the ‘Terminal’ (‘Terminal emulator’) inside the ‘Unity’ desktop rather than the ‘login-shell’.
How to do it …
Basically for copying a file or a folder, we have to know three main things. First you have to know its name and the ‘path’ (location) and also the path of the destination (where you want it to be copied). After you’ve figured that out, the rest is just bloody easy :).
For copying files and folders we’ll use a built in command-line utility called ‘cp’ and for figuring out the names and the path we’ll use another one called ‘dir’.
To copy a file into another location I’d use a built in command called ‘cp’ in the below format.
cp -vi source-file ‘s — path destination’s-path
To do the same to a folder, I’ll use the ‘-a’ argument as shown below.
cp -via source-folder’s-path destination’s-path
You can also use ‘-r’ instead of ‘-a’ but that will replace some of the data of the files (not their content but things like ‘created date’ and ‘accessed date’ etc thus I prefer to use ‘-a’ so the data will be copied as it is. It’s also the way file managers of the desktops seem to be copying files and folders, I think).
What is that ‘-v’ argument?
The ‘-v’ argument gives you a simple output (basically tells you what file it’s currently copying). Running it with ‘Mr. -v’ 😉 …
This is very useful because by default, while copying one or multiple files, ‘cp’ doesn’t give you any output (unless there’s an error). So other than the HDD’s LED indicator, you’d wouldn’t know what going on. As you can see, without the ‘-v’, until it finishes, you wouldn’t know anything about the process …
What is the ‘-i’ argument’?
If some of your files in the destination have the same names as the files that are being copied, then ‘cp’ automatically overwrite them!. But when you use the ‘-i’ argument, it’ll ask you before overwriting. So I highly recommend that you use it, all the time.
If your file or the folder has spaces in its name …
Let’s say I have a file called ‘test audio.mp3’ (note the space between ‘test’ and ‘audio.mp3’), then in the command-line, this file will be listed as ‘test\ audio.mp3’ not ‘test audio.mp3’.
This is because, before each space in a file’s name, the command-line assigns a ‘\’ to it. If you have another file called ‘Ubuntu 12.04 review.avi’, then in the command-line it’ll be listed as ‘Ubuntu\ 12.04\ review.avi’. So by remembering this rule, if you know the file’s name, than you can easily figure its name in CLI.
Even if you don’t know the name, you can use the ‘dir’ command to list and find folder/file name with ease. Let’s say that I wanted get a list of all the files in my ‘Music’ folder, then I’ll use the below command.
By default, ‘dir’ does not show hidden files. For that, you’ll have to use it with the ‘-a’ attribute. So to view all the files inside the ‘Music’ folder, I’ll use the below command.
By simply using ‘dir’ will show you the folders and files inside your current location. So if I used it after logging into the shell (or in ‘Terminal’) then it’ll just show me the content inside my ‘Home’ folder as shown below.
Also remember that, whenever you insert a removable media (USB drive for example), or while accessing other partitions of your HDD or opening optical disc’s content etc, they’ll all first be ‘mounted’ (think of it as temporarily opening the content of a storage device into a folder where your OS is installed) in a location called ‘/media’.
So, after inserting your USB disk (or any other), because you’re gonna be needing its ‘mounted’ (opened) folder’s path while coping files to it later, then you can simply enter the below command in your Terminal and it’ll list all the currently mounted storage devices (=paths) in your OS.
In this case, my USB drive is called ‘GAYAN’ and it’s opened on a folder called ‘GAYAN’ under the ‘/media’ location.
Let’s say that I need to copy a recorded audio file inside the ‘Music’ folder and don’t remember the full file name, then I’ll use the above mentioned ‘dir’ command to get its full name.
So the full path of the source file that I want to copy in this case is:
As I need to copy this audio file to my USB drive mounted at ‘/media/GAYAN’, the full path of the destination is:
So in order to copy the ‘audio-recording1.mp3’ into ‘GAYAN’ USB drive, I’ll use the below command.
cp -vi /home/gayan/Music/audio-recording1.mp3 /media/GAYAN
For any file or a folder that’s inside my ‘Home’, I can bypass typing ‘/home/gayan’ part (in your computer, ‘gayan’ will be replaced by your user name), so the short version of the above command is:
cp -vi Music/audio-recording1.mp3 /media/GAYAN
If I wanted to copy all the content of the folder ‘Music’, as it’s a folder, I’ll use the ‘cp’ command with the ‘-a’ argument:
Make sure to use ‘-v’ argument and ‘-a’ when copying folders, and replace source file name (and path) and destination path with your own ones. If you want to automatically create a folder inside the destination and copy the file/folder inside it, then add a folder name to the end of the destination’s path.
So if I wanted to copy the ‘Music’ folder to a new folder called ‘music-backup’, then I’ll use the below command instead of the above one.
cp -via Music /media/GAYAN/music-backup
Well, that’s pretty much it. Once you get familiar with finding the name and the path of the file/folder that you want to copy, there isn’t a whole lot to it. If you want to know more about these two commands, then use the below commands to read their manuals.
Related Posts
Gayan
An RHCE, ‘Linux’ user with 14+ years of experience. Extreme lover of Linux and FOSS. He is passionate to test every Linux distribution & compare with the previous release to write in-depth articles to help the FOSS community.
13 thoughts on “How to Use the Command-line to Copy files and folders in Ubuntu Linux?”
Thank you for this information, it is very helpful.
However I am having an issue with my desktop–it does not load, so I must use Ctrl+Alt+f1 to log in (as in your example), however when I try dir /media the thumb drive I have (waiting to copy files) does not show up–NOTHING shows up (I also have a disk in the drive to write to–if that is even possible.) Do I have to mount them to use them? if so, how do I do that? Thanks!
It seems that you’ll have to manually mount the USB pendrive first. You can also write your content to a disk, but doing so using the command-line can be a bit difficult, specially if your content is scattered in multiple locations. If interested doing that, then this page can help you out.
If not, then you can follow the below steps for mounting the USB pendrive and copying the data later.
Step 1:
Enter the below command into the Terminal window. It’ll show you a list of currently attached disk drives, USB storage devices etc, and then by using that information, you can easily mount the desired USB drive.
Now, after adding a USB pendrive and logging into the system (using Ctrl + Alt + F1), I tested this and below is the output that I received (your output should vary, depending on the attached drives …).
Disk /dev/sda: 320.1 GB, 320072933376 bytes
255 heads, 63 sectors/track, 38913 cylinders, total 625142448 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x0bbcfd15
Device Boot Start End Blocks Id System
/dev/sda1 * 2048 206847 102400 7 HPFS/NTFS/exFAT
/dev/sda2 206848 61442047 30617600 7 HPFS/NTFS/exFAT
/dev/sda3 61442048 606210047 272384000 7 HPFS/NTFS/exFAT
/dev/sda4 606212094 625141783 9464845 5 Extended
/dev/sda5 606212096 625141783 9464844 83 Linux
Disk /dev/sdb: 7742 MB, 7742685184 bytes
255 heads, 63 sectors/track, 941 cylinders, total 15122432 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000
Device Boot Start End Blocks Id System
/dev/sdb1 * 2048 15122431 7560192 b W95 FAT32
As you can see this command lists my drives and their partitions (the output is more clear on the Terminal window than displayed here).
The ‘/dev/sda’ is my primary HDD because it lists the capacity as 320.1 GB (it has 5 partitions ‘/sda1’ … ‘/sda5’), and the second one, ‘/dev/sdb’ is my USB pendrive (7742MB). The partition on the USB drive is ‘/dev/sdb1’, which is what we’re interested in.
If you have no other USB storage device attached to your PC (other than the pendrive), then you should too mount the ‘/dev/sdb1’. But you can always figure that out by having a look at this output.
Before we can mount this, enter the below command (this creates a folder into which we’re going to mount the pendrive).
Then enter the below command to actually mount it.
Note: Replace the ‘/sdb1’ according to the ‘output’ of the ‘fdisk -l’ command. That’s it. Now you should be able to copy your data to the pendrive as shown in the article, but make sure to add ‘sudo’ argument while copying (because we just mounted the pendrive with ‘sudo’ permissions).
(Optional)Quick tip: If you have to copy files (or folders) individually and they happen to contain ‘spaces’ in their names, then use the double quotation mark with the ‘cp’ command while entering the path, otherwise it’ll fail (this has nothing to do while copying a folder that contain multiple files that have ‘spaces’ in their names … it only applies when you copy files or folders individually).
For instance, if I have a file (or a folder) called ‘cool video 4’ in my Home directory, then if I use the below command while copying, it’ll fail saying there’s no such file.
The correct command will be the below one.
Hope this helps. Good luck (by the way, if you can create a Live USB of Ubuntu, then use that to copy your files because it’s much easier 🙂 ).
Apparently I’m missing something (I’m sorry to be so dense). I attempted multiple times to copy files to /media/pen with no success, so I made a live USB to try that. I have my 150GB partition mounted and attempted to drag and drop files. I keep getting a message that “the folder ____ cannot be handled because you do not have permissions to read it” (I have tried a file on the desktop as well as my .thunderbird folder in my home folder). I was able to drag and drop a picture from the desktop to the pen drive…but no file folder or open office file can be moved. I guess more instruction is needed if you don’t mind walking me through more of this…? Thank you.
BTW, when I right click on the 150GB drive and go to permissions, it says Owner is root with folder access to create and delete files (which is grayed out and cannot be changed). Group is root with folder access to access files (also grayed out). Others has nothing listed and folder access is to access files (also grayed out) and at the bottom of the box it says “you are not the owner, so you cannot change these permissions”
Okay, once you’ve boot into the Live desktop, open the Terminal and enter the below command …
This should open up the file manager with ‘root’/’sudo’ privileges and now you should be able to copy the files.
Ok, I tried using sudo nautilus and still got errors when trying to copy so I looked it up and tried sudo nautilus &> /dev/null
SOMEHOW I got it to work–SOME of the time. However, I still can’t copy a couple folders from the desktop to the thumb drive. I was able to get to one of the (hidden) folders I wanted to copy for my son and actually could change the permissions, but they did not stick even though I clicked the button at the bottom to have permissions carry to all folders/files(?)
I want to thank you for your help so far as it’s the farthest I’ve gotten in weeks!
I just unapproved my first answer because I found a way to copy data using a Live desktop session. I had not tried something like this in years (which is why I got a bit confused, sorry about that), so I created a live USB session for testing this out for you. I just followed my own advice, you know running ‘sudo nautilus’ as I told you, but it too, like yours, failed. So I played around a bit and found a way backup data. So this is what you should do.
Step 1: Start the Live Ubuntu session and once you’re logged into the desktop open ‘Nautilus’ (file manager) from the Application Launcher as usual.
*. If you haven’t plugged in the USB drive that you’re going to backup your data, then insert it also.
Step 2: If ‘Nautilus’ doesn’t automatically opens the USB drive, click on its icon from under the ‘Devices’. We just want to make sure that it’s mounted.
Step 3: Again from under the ‘Devices’, select the partition where the broken Ubuntu is installed and ‘Nautilus’ should mount it for you. When done simply close ‘Nautilus’.
Step 4: Now open Terminal and enter the below command.
This will ask you to enter a new password for the ‘root’ user and upon entering one will enable it (which is disabled by default). Now simply enter a password (it’ll ask twice). When done go to the next step.
Step 5: Now enter the below command and when asked, simply enter the password that you just entered.
Once you enter the password you’ll be logged in as the actual ‘root’ (administrator) in a Terminal session. When done, go to the next step (don’t close the Terminal window).
Step 6: Now all we have to do is to open ‘Nautilus’ with the actual ‘root’ permissions. For that, simply enter the below command
*. The Terminal window might give you errors, just ignore them.
That’s it!. Now you should see under the ‘Devices’ not all the available partitions/devices, but only the ones that you mounted previously (USB drive and the broken Ubuntu partition). Now navigate your way into the Ubuntu partition where your data resides and now you should be able to ‘copy’ & ‘paste’ your data freely.
If you encounter any issues, feel free to contact me.
Источник