Copy files and directories in Ubuntu

In this article, we would cover how to copy files and directories in Ubuntu. When doing the same through a Graphical User Interface (GUI), it seems pretty easy. But, when it comes to using Command-line Interface (CLI) for copying files/directories then, we need to remember certain command options to make things work.

If you have been using Graphical User Interface to interact with files and directories then, initially it might look like bit of a challenge. But, in reality – once you understand what needs to be done then, it becomes pretty easy.

We illustrate how to copy files in next section. And, then directories later.

Copy files in Ubuntu

Use cp command-line utility to copy both files and directories. Consider a file – xyz.

Example I. Copy xyz file to ~/Downloads directory –

cp xyz ~/Downloads

If we want to copy a file to some directory then, we need to first provide the file_name and then directory_path, to which we want to copy the file. This is what it looks like –

cp <file_name> <directory_path>

We would like to add here that, if we haven’t open the current directory in our terminal then, we need to provide complete path name of our file. For instance,

cp /home/$USER/Documents/xyz ~/Downloads

Example II. Copy xyz file in the same directory but with a different file_name i.e. abc

cp xyz abc

This ensures we have both the files i.e. abc, xyz in the same directory.

Example III. Copy in interactive mode. It prompts us that the file already exists. Continuing with the above example. If we have already abc and xyz files in the same directory and we again try to run the command with -i option, then it will ask us whether to overwrite the file or not?

cp -i xyz abc

It will prompt –

cp: overwrite 'abc'?

Answer it with ‘y‘ if you want to overwrite and ‘n‘ if you don’t.

Example IV. If you want to preserve the original file attributes, use –preserve option. Default preserve attributes include – mode, timestamps and ownership.

cp --preserve xyz abc

Copy directories in Ubuntu

In this section, we would see how we can copy directories in Ubuntu using cp command-line utility. We have a directory with directory_name dir1/

Example I. Copy dir1/ to ~/Downloads directory –

cp -r dir1/ ~/Downloads

where, -r option copies directories recursively. This means it copies the contents of dir1/ as well. Not just the directory itself.

Example II. If you want to copy the entire directory dir1/ in the current directory –

cp -r dir1/ dir2/

This creates a directory dir2/ which is a copy of dir1/

Example III. To preserve original directory attributes, we use –preserve option.

cp -r dir1/ dir2/ --preserve

mode, timestamps and ownership are few –preserve options.

In conclusion, we have discussed how to copy files and directories in Ubuntu here.

Similar Posts