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.

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.
Читайте также:  Linux microsoft surface pro

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.

Читайте также:  Nvidia driver installer linux

Источник

Копирование файлов и директорий: команда cp в Linux и MacOS

Перевод статьи «Copy a Directory in Linux – How to cp a Folder in the Command Line in Linux and Unix (MacOS)».

Для копирования файлов или директорий (папок) в Unix-подобных операционных системах (Linux и MacOS) используется команда cp .

Команда cp относительно простая, но ее поведение может изменяться в зависимости от передаваемых опций и того, что именно (файлы или директории) и куда копируется.

Для просмотра документации или руководства по использованию команды cp выполните в терминале команду man cp :

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

Примечание редакции Techrocks. Также для получения справки можно воспользоваться командой cp —help .

В своей базовой форме эта команда принимает в качестве инпута источник, который вы хотите скопировать, и «пункт назначения» — то, куда именно вы хотите его скопировать. Источником может быть файл, несколько файлов или вообще директория.

cp [OPTIONS] source_file target_file

Как создать копию файла в текущей директории

Чтобы создать копию файла в той же директории, нужно передать команде cp имя исходного файла и имя, которое нужно дать файлу-копии.

Допустим, у вас есть файл a.txt и вы хотите создать его копию под именем b.txt в той же директории:

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

Для справки: команда ls выводит список файлов в текущей директории.

По умолчанию команда cp использует в качестве пути к файлам вашу текущую директорию.

Как скопировать файл в другую директорию

Чтобы скопировать файл в директорию, отличную от вашей текущей, нужно просто указать путь к ней:

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

После выполнения команды cp ранее пустая directory-1 содержит файл a.txt.

Примечание редакции Techrocks. В примере показан относительный путь к директории. Две точки перед слэшем означают «родительская директория». Допустим, ваша текущая директория — directory-2, которая находится в директории parent_directory. Команда ls ../directory-1/ выведет список файлов в directory-1, которая тоже находится в parent_directory.

По умолчанию копируемый файл сохраняет свое имя, но вы можете указать любое другое:

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

Как скопировать несколько файлов в другую директорию

Чтобы одновременно скопировать несколько файлов, вы можете передать команде несколько источников, а в конце указать пункт назначения:

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

В этом примере оба файла (first.txt и second.txt) были скопированы в директорию directory-1.

Примечание: при передаче нескольких источников последний аргумент обязательно должен быть директорией.

Как скопировать одну директорию в другую

Если вы попытаетесь передать команде cp в качестве источника имя директории, вы получите ошибку:

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

Для копирования директории целиком нужно добавить флаг -r (или -R , или —recursive ), указывающий, что копировать надо рекурсивно:

Читайте также:  Firefox linux пропал звук

В следующем примере у нас есть две директории (directory-1 и directory-2), расположенные в нашей текущей директории. В directory-1 есть файл a.txt. Мы рекурсивно копируем directory-1 в directory-2. После этого в нашей текущей директории по-прежнему есть directory-1 и directory-2, при этом в directory-2 есть копия directory-1, содержащая файл a.txt.

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

Копирование директории целиком и копирование всего содержимого из директории

Примечание редакции Techrocks. Когда мы попробовали применить эту инструкцию в терминале Linux, у нас ничего не вышло. В одной статье мы нашли, что описанный функционал работает в MacOS, но не в Linux. Поэтому здесь мы сначала приведем перевод инструкций автора, а затем от себя дополним их.

При копировании директории есть интересный нюанс. Если директория, которую вы указываете как пункт назначения, уже существует, вы можете скопировать в нее либо все содержимое директории-источника, либо всю директорию-источник целиком. Выбор регулируется добавлением конечного слэша / к имени директории-источника.

Вот описание опции -R в мануале ( man ):

Если файл_источник является директорией, cp копирует директорию и все поддерево, подключенное к этой точке. Если файл_источник заканчивается на / , копируется содержимое этой директории, а не сама директория.

Поэтому, если вы хотите скопировать в другое место только файлы и папки из директории-источника, добавьте в конце слэш / .

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

Если вы хотите скопировать всю папку вместе со всем ее содержимым, не добавляйте в конце слэш / .

Для пользователей Linux: после слэша нужно добавить точку. Если хотите почитать более подробно, вот хорошая статья на Хабре.

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

Как предотвратить перезапись файлов при копировании

По умолчанию команда cp перезаписывает существующие файлы. Для примера создадим в текущей директории файл a.txt с текстом A, а в директории directory-1 — файл a.txt с текстом B. При копировании файла a.txt из текущей директории в directory-1 файл a.txt перезаписывается (в его содержимом было B, стало A).

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

Примечание: команда cat среди прочего служит для вывода содержимого файлов на экран.

Есть два способа предотвратить перезапись файлов.

Флаг —interactive

Чтобы при возможной перезаписи получить предупреждение, можно добавить к команде cp флаг -i (или —interactive):

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

Флаг —no-clobber

Флаг -n (или —no-clobber ) позволяет предотвращать перезапись по умолчанию, не спрашивая пользователя:

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

На этом примере видно, что благодаря флагу -n содержимое файла directory-1/a.txt не было перезаписано.

Другие опции

Команде cp можно передавать много других полезных опций. Например, -v для «многословного» вывода или -f для «принудительного» выполнения. Я советую почитать страницу man , чтобы хотя бы знать, какие есть варианты.

Источник

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