Copying files and directories in linux

Copy Files and Directories in Linux

Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.

Copying a file is one of the most common Linux tasks. Ubuntu and other Linux distributions use the cp command to copy one or more files, and to copy entire directories. This guide explains how to use the cp command to copy files on Linux. It also lists the different variations of this command and describes the different cp command options.

An Introduction to cp

The cp command is used to copy one or more files on a Linux system to a new location. It is similar to the mv command, except it does not move or remove the original file, which remains in place. Like most Linux commands, cp is run using the command line of a system terminal.

The cp command allows users to copy a file to either the same directory or a different location. It is also possible to give the copy a different name than the original file. The -r option enables the cp command to operate recursively and copy a directory along with any files and subdirectories it contains. cp has a number of options, allowing users to run it interactively, use verbose mode, or preserve the file attributes of the original.

Users must have sudo privileges to copy protected files. Otherwise, sudo is not required.

Before You Begin

  1. If you have not already done so, create a Linode account and Compute Instance. See our Getting Started with Linode and Creating a Compute Instance guides.
  2. Follow our Setting Up and Securing a Compute Instance guide to update your system. You may also wish to set the timezone, configure your hostname, create a limited user account, and harden SSH access.

This guide is written for a non-root user. Commands that require elevated privileges are prefixed with sudo . If you are not familiar with the sudo command, see the Users and Groups guide.

Читайте также:  One time password linux

How to Use the cp Command to Copy Files and Directories in Linux

The cp command works similarly on most Linux distributions. The command operates in four basic modes.

  • Copies a file to the same directory. The new file must have a different name.
  • Copies a file to a different directory. It is possible to rename the file or retain the old name.
  • Copy multiple files to a different target directory.
  • Recursively copy the contents of a directory, including subdirectories, to a different target directory.

There are a number of concerns to be aware of when using cp . For instance, cp does not display a warning when overwriting an existing file. This situation occurs when copying a file to a new directory already containing a file with the same name. This problem is more likely to happen when copying multiple files. To avoid this problem, users can use interactive mode to force Linux to request confirmation before overwriting a file.

cp is often used in conjunction with the ls command. ls lists the contents of the current directory. This is handy for confirming the exact name and location of the source files and directories.

Some of the most important cp command options include the following:

  • -f : Forces a copy in all circumstances.
  • -i : Runs cp in interactive mode. In this mode, Linux asks for confirmation before overwriting any existing files or directories. Without this option, Linux does not display any warnings.
  • -p : Preserves the file attributes of the original file in the copy. File attributes include the date stamps for file creation and last modification, user ID, group IP, and file permissions.
  • -R : Copies files recursively. All files and subdirectories in the specified source directory are copied to the destination.
  • -u : Overwrites the destination file only if the source file is newer than the destination file.
  • -v : Runs cp in verbose mode. This mode provides extra information on the copying process. This is useful for keeping track of progress when copying a large number of files.

The options -H , -L , and -P indicate how the cp command should process symbolic links. See the cp man page for a full description of cp and symbolic links. The options for cp vary between Linux distributions. A list for Ubuntu 22.04 LTS is available in the Ubuntu cp documentation.

How to Copy a File in Linux

One common use of cp is to make a second copy of the source file in the same directory. Supply a different name for the copy to differentiate it from the original. A common convention is to add an extra extension such as .bak or .cp to the existing file name. For example, a standard name for a backup copy of archive.txt is archive.txt.bak .

Читайте также:  Установить труконф на линукс

The cp command operates in the context of the current working directory. However, files can be specified using either an absolute or relative path. Here is the basic cp command to copy a file within the same directory.

Источник

Copy a Directory in Linux – How to cp a Folder in the Command Line in Linux and Unix (MacOS)

Copy a Directory in Linux – How to cp a Folder in the Command Line in Linux and Unix (MacOS)

To copy files or directories in Unix-based operating systems (Linux and MacOS), you use the cp command.

The cp command is a relatively simple command, but its behavior changes slightly depending on the inputs (files vs directories) and the options you pass to it.

To view the documentation or manual for the cp command, run man cp at your terminal:

$ man cp NAME cp -- copy files SYNOPSIS cp [OPTIONS] source_file target_file cp [OPTIONS] source_file . target_directory . 

The basic form of this command takes an input source (or sources) that you want to copy (files or directories) and a destination to copy the files or directories to:

cp [OPTIONS] source_file target_file

How to copy a file to the current directory

To copy a file, pass the file you want to copy and the path of where you want to copy the file to.

If you have a file named a.txt , and you want a copy of that file named b.txt :

$ ls a.txt $ cp a.txt b.txt $ ls a.txt b.txt

By default the cp command uses your current directory as the path.

How to copy a file to another directory

To copy a file to a directory that is different from your current directory, you just need to pass the path of the other directory as the destination:

$ ls ../directory-1/ $ cp a.txt ../directory-1/ $ ls ../directory-1/ a.txt 

After the cp command, the previously empty directory-1 now contains the file a.txt .

By default the copied file receives the name of the original file, but you can also optionally pass a file name as well:

$ cp a.txt ../directory-1/b.txt $ ls ../directory-1/ b.txt

How to copy multiple files to a directory

To copy more than one file at a time you can pass multiple input sources and a directory as destination:

$ ls ../directory-1/ $ cp first.txt second.txt ../directory-1/ $ ls ../directory-1/ first.txt second.txt 

Here the two input sources ( first.txt and second.txt ) were both copied to the directory directory-1 .

How to copy a directory to another directory

If you try to pass a directory as the input source, you get this error:

$ cp directory-1 directory-2 cp: directory-1 is a directory (not copied).

To copy a directory, you need to add the -r (or -R ) flag—which is shorthand for —recursive :

$ ls directory-1 a.txt $ cp -r directory-1 directory-2 $ ls directory-1 directory-2 $ ls directory-2 a.txt

Here directory-1 containing the file a.txt is copied to a new directory called directory-2 —which now also contains the file a.txt .

Читайте также:  Рабочие окружения linux kde

How to copy the entire directory vs the contents of the directory

There is an interesting edge case when you copy a directory: if the destination directory already exists, you can choose whether to copy the contents of the directory or the entire directory by adding or removing a trailing / from your input.

Here’s the description from the -R option of the man page:

If source_file designates a directory, cp copies the directory and the entire subtree connected at that point. If the source_file ends in a /, the contents of the directory are copied rather than the directory itself.

If you want to copy just the contents of the directory into another directory, add a trailing / to your input.

If you want to copy the contents of the directory and the directory folder itself into another directory, don’t add a trailing / :

$ ls directory-1 directory-2 $ ls directory-2 $ cp -r directory-1 directory-2 $ ls directory-2 directory-1 $ ls directory-2/directory-1 a.txt

Here you can see that because directory-2 already exists—and the input source didn’t have a trailing / —both the contents of directory-1 and the directory itself was copied into the destination.

How to prevent overwriting files with cp

By default, the cp command will overwrite existing files:

$ cat a.txt A $ cat directory-1/a.txt B $ cp a.txt directory-1/a.txt $ cat directory-1/a.txt A

There are two ways to prevent this.

The interactive flag

To be prompted when an overwrite is about to occur, you can add the -i or —interactive flag:

$ cp -i a.txt directory-1/a.txt overwrite directory-1/a.txt? (y/n [n])

The no-clobber flag

Or, to prevent overwrites without being prompted, you can add the -n or —no-clobber flag:

$ cat a.txt A $ cat directory-1/a.txt B $ cp -n a.txt directory-1/a.txt $ cat directory-1/a.txt B

Here you can see that thanks to the -n flag the contents of directory-1/a.txt were not overwritten.

Other options

There are many other useful options to pass to the cp command: like -v for «verbose» output or -f for «force.»

I highly encourage you to read through the man page for all of the other useful options.

If you liked this tutorial, I also talk about topics like this on Twitter, and write about them on my site.

Источник

Оцените статью
Adblock
detector