- Linux Copy File Command [ cp Command Examples ]
- cp Command Syntax
- Linux Copy File Examples
- Copy a file to another directory
- Verbose option
- Preserve file attributes
- Copying all files
- Recursive copy
- Linux copy file command with interactive option
- Verbose output with cp command
- Conclusion
- Копирование файлов в Linux
- Утилита копирования файлов cp
- Синтаксис и опции
- Примеры копирования файлов в linux
- Копирование файлов по регулярным выражениям в Linux
- Копирование содержимого файлов в Linux
- Специальное копирование файлов в Linux с помощью tar
- Выводы
- How to Copy Files and Directories in Linux
- Using the cp Command to Copy Files and Directories in Linux
- Additional Options
- How to Copy File to Another Directory in Linux
- Copy Multiple Files from One Directory to Another in Linux
- Copy Using rsync Command
- Other Options
Linux Copy File Command [ cp Command Examples ]
cp Command Syntax
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Terminal app/Shell prompt |
Est. reading time | 3 mintues |
The syntax is as follows to copy files and directories using the cp command:
cp SOURCE DEST
cp SOURCE DIRECTORY
cp SOURCE1 SOURCE2 SOURCE3 SOURCEn DIRECTORY
cp [OPTION] SOURCE DEST
cp [OPTION] SOURCE DIRECTORY
Where,
- In the first and second syntax you copy SOURCE file to DEST file or DIRECTORY.
- In the third syntax you copy multiple SOURCE(s) (files) to DIRECTORY.
Note: You need to type the cp command at the dollar sign ($) prompt. This prompt means that the shell is ready to accept your typed commands. Do not type the dollar ($) sign. You need to open the Terminal app to use cp command on a Linux.
Linux Copy File Examples
To make a copy of a file called file.doc in the current directory as newfile.doc, enter:
$ cp file.doc newfile.doc
$ ls -l *.doc
Sample outputs:
You can copy multiple files simultaneously into another directory. In this example, copy the files named main.c, demo.h and lib.c into a directory named backup:
$ cp main.c demo.h libc. backup
If backup is located in /home/project, enter:
$ cp main.c demo.h libc. /home/project backup
Copy a file to another directory
To copy a file from your current directory into another directory called /tmp/, enter:
$ cp filename /tmp
$ ls /tmp/filename
$ cd /tmp
$ ls
$ rm filename
Verbose option
To see files as they are copied pass the -v option as follows to the cp command:
Preserve file attributes
To copy a file to a new file and preserve the modification date, time, and access control list associated with the source file, enter:
$ cp -p file.txt /dir1/dir2/
$ cp -p filename /path/to/new/location/myfile
This option ( -p ) forces cp to preserve the following attributes of each source file in the copy as allowed by permissions:
- Modification time/date
- Access time
- File flags
- File mode
- User ID (UID)
- Group ID (GID)
- Access Control Lists (ACLs)
- Extended Attributes (EAs)
Copying all files
The star wildcard represents anything i.e. all files. To copy all the files in a directory to a new directory, enter:
$ cp * /home/tom/backup
The star wildcard represents anything whose name ends with the .doc extension. So, to copy all the document files (*.doc) in a directory to a new directory, enter:
$ cp *.doc /home/tom/backup
Recursive copy
To copy a directory, including all its files and subdirectories, to another directory, enter (copy directories recursively):
$ cp -R * /home/tom/backup
Linux copy file command with interactive option
You can get prompt before overwriting file. For example, if it is desired to make a copy of a file called foo and call it bar and if a file named bar already exists, the following would prompt the user prior to replacing any files with identical names:
cp -i foo bar
- 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 ➔
Verbose output with cp command
If you pass the -v to the cp, it makes tells about what is going on. That is verbose output:
cp -v file1 file2
cp -avr dir2 /backups/
Conclusion
This page explained cp command that is used for copying files under Linux and Unix-like systems. For more info see man pages: ls(1).
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Копирование файлов в Linux
Копирование файлов — одна из задач, наиболее часто возникающих перед пользователями персонального компьютера. Конечно, можно открыть файловый менеджер, войти в нужную папку и скопировать файл с помощью контекстного меню — тут не о чем говорить. Но в этой статье я хотел бы рассмотреть копирование файлов в Linux с помощью терминала.
Не всегда есть доступ к файловому менеджеру: из-за различных поломок графическая оболочка на домашнем компьютере может быть недоступна, а на серверах используется только консольный интерфейс. К тому же копирование файлов Ubuntu через терминал намного эффективнее, и вы сами в этом убедитесь. Сегодня мы рассмотрим не только обычное копирование командой cp Linux, но и не совсем обычное: с помощью tar и find.
Утилита копирования файлов cp
Название утилиты cp — это сокращение от Copy, что означает копировать. Утилита позволяет полностью копировать файлы и директории.
Синтаксис и опции
Общий синтаксис cp выглядит вот так:
$ cp опции файл-источник файл-приемник
$ cp опции файл-источник директория-приемник/
После выполнения команды файл-источник будет полностью перенесен в файл-приемник. Если в конце указан слэш, файл будет записан в заданную директорию с оригинальным именем.
Утилита имеет несколько интересных опций, которые могут сильно помочь при нестандартных задачах копирования, поэтому давайте их рассмотрим:
- —attributes-only — не копировать содержимое файла, а только флаги доступа и владельца;
- -f, —force — перезаписывать существующие файлы;
- -i, —interactive — спрашивать, нужно ли перезаписывать существующие файлы;
- -L — копировать не символические ссылки, а то, на что они указывают;
- -n — не перезаписывать существующие файлы;
- -P — не следовать символическим ссылкам;
- -r — копировать папку Linux рекурсивно;
- -s — не выполнять копирование файлов в Linux, а создавать символические ссылки;
- -u — скопировать файл, только если он был изменён;
- -x — не выходить за пределы этой файловой системы;
- -p — сохранять владельца, временные метки и флаги доступа при копировании;
- -t — считать файл-приемник директорией и копировать файл-источник в эту директорию.
Примеры копирования файлов в linux
Теперь, когда вы знаете основные опции, можно перейти к практике. Например, мы хотим скопировать некую картинку из домашней папки в подкаталог pictures:
Или можем явно указать имя новой картинки:
Копирование папок осуществляется с помощью ключа -r:
После выполнения этой команды копирования
/папка будет скопирована в папку
/Документы. Главное, не забывайте поставить слэш в конце выражения или использовать опцию -t. Иначе папка
/документы будет перезаписана.
По умолчанию команда cp Linux перезаписывает существующие файлы или папки, но можно заставить утилиту спрашивать, нужно ли перезаписывать каждый файл, если вы не уверены в правильности составления команды:
Есть и противоположная опция -n, означающая «никогда не перезаписывать существующие файлы».
Опция -u полезна в следующем случае: вы знаете или предполагаете, что в директории, куда копируется файл, есть старая его версия, тогда оператор -u выполнит замену на новую версию:
Сp также поддерживает специальные символы замены * и ?. Например, следующая команда скопирует все файлы, начинающиеся на test:
Если нужно применить более сложные регулярные выражения, придётся комбинировать утилиту cp с find или egrep.
В случае, если важно сохранить права доступа к файлу и его владельца, нужно использовать опцию -p:
Для упрощения использования команды можно применять синтаксис фигурных скобок. Например, чтобы создать резервную копию файла, выполните:
Будет создан файл с таким же именем и расширением .bak
По умолчанию в cp не отображается прогресс копирования файла, что очень неудобно при работе с большими файлами, но его можно легко посмотреть с помощью утилиты cv.
Копирование файлов по регулярным выражениям в Linux
В утилите find можно применять различные условия и регулярные выражения для поиска файлов. Я уже немного писал о ней в статье как найти новые файлы в Linux. Мы можем скопировать все найденные с помощью find файлы, вызвав для каждого из них команду cp. Например, копируем все файлы в текущей директории, содержащие в имени только цифры:
find . -name 3 -exec cp <>
Здесь точка указывает на текущую директорию, а параметр name задает регулярное выражение. Параметром exec мы задаем, какую команду нужно выполнить для обнаруженных файлов. Символ <> — подставляет имя каждого файла.
Но не find‘ом единым такое делается. То же самое можно получить, запросив список файлов директории в ls, отфильтровав его по регулярному выражению egrep и передав имена файлов по очереди в cp с помощью xargs:
/ | egrep ‘[a-zA-Z]’ | xargs cp -t
Это не совсем удобный способ копировать файлы Linux, но всё же он возможен. Будут скопированы все файлы из домашней директории, содержащие в имени только английские буквы.
Копирование содержимого файлов в Linux
Вы можете не только копировать сами файлы, но и управлять их содержимым. Например, склеить несколько файлов в один или разрезать файл на несколько частей. Утилита cat используется для вывода содержимого файла, в комбинации с операторами перенаправления вывода Bash вы можете выполнять копирование содержимого файла Linux в другой файл. Например:
cat файл1 > файл2
Если файл был не пустым, он будет перезаписан. Или мы можем склеить два отдельных файла в один:
cat файл1 файл2 > файл3
Специальное копирование файлов в Linux с помощью tar
Linux интересен тем, что позволяет выполнять одно и то же действие различными путями. Копирование в Linux тоже может быть выполнено не только с помощью cp. При переносе системных файлов в другой каталог, резервном копировании системных файлов и т.д. важно чтобы сохранились атрибуты, значения владельцев файлов и символические ссылки как они есть без какой-либо модификации.
Утилита cp тоже может справиться с такой задачей? если указать опцию -p, но можно использовать утилиту архивации tar. Мы не будем создавать никаких файлов архивов, а построим туннель. Первая часть команды пакует файл и отправляет на стандартный вывод, а другая сразу же распаковывает в нужную папку:
tar cf — /var | ( cd /mnt/var && tar xvf — )
Здесь мы полностью копируем содержимое папки /var в папку /mnt/var. Так вы можете копировать папку Linux, причём абсолютно любую или даже целую операционную систему.
Выводы
Теперь вы знаете, как выполняется копирование файлов Ubuntu и в Linux в целом. Как видите, в терминале это выполняется намного быстрее и эффективнее, чем с помощью графического интерфейса, если помнить нужные команды. Если у вас остались вопросы, спрашивайте в комментариях!
Источник
How to Copy Files and Directories in Linux
Home » SysAdmin » How to Copy Files and Directories in Linux
This guide will show you how to copy files and directories in Linux by executing commands from the command line. Furthermore, the commands listed below detail how to create system-wide backups or filter out and copy only specific files.
Note: These Linux commands can only be run from a terminal window. If your version of Linux boots to a desktop graphical interface, launch a terminal window by pressing CTRL-ALT-F2 or CTRL-ALT-T.
Using the cp Command to Copy Files and Directories in Linux
The cp command is the primary method for copying files and directories in Linux. Virtually all Linux distributions can use cp . The basic format of the command is:
This Linux command creates a copy of the my_file.txt file and renames the new file to my_file2.txt.
By default, the cp command runs in the same directory you are working in. However, the same file cannot exist twice in the same directory. You’ll need to change the name of the target file to copy in the same location. Some users will add _old, some will add a number, and some will even change the three-letter extension (e.g., .bak instead of .txt).
You may not get a warning before Linux overwrites your file – be careful, or see below for the –i option.
Additional Options
Additional options can be used in combination with the cp command:
- –v verbose: shows the progress of multiple copied files
- –ppreserve: keeps the same attributes, like creation date and file permissions
- –f force: force the copy by deleting an existing file first
- –i interactive: prompts for confirmation, highly advised
- –Rrecursive: copies all files and subfolders in a directory
- –u update: copy only if source is newer than destination
Note: The -p (preserve) option forces the system to preserve the following source file attributes: modification time, access time, user ID (UID), group ID (GID), file flags, file mode, access control lists (ACLs), and extended attributes (EAs).
How to Copy File to Another Directory in Linux
To copy a file from the directory you’re working in to a different location, use the command:
You don’t need to rename the file unless there’s already one with the same name in the target directory.
To specify a path for the source file:
This lets you copy without having to change directories. The cp command will create the /new_directory if it doesn’t exist.
To rename and copy a file to a different path:
This option is useful for creating backups of configuration files, or for copying data to a storage device.
Note: Learn how to move directories in Linux.
Copy Multiple Files from One Directory to Another in Linux
You may need to copy more than one file at a time.
List each file to be copied before the target directory:
This example created a copy of all three files in the /new_directory folder.
Use a wildcard to specify all files that share a string of characters:
This would find all the files with the .jpg extension in the /pictures directory, and copy them into the /new_directory folder.
To copy an entire folder and its subfolders and files, use the –R option:
–R stands for recursive, which means “everything in that location.” This would copy all the files, as well as all the directories, to the /new_directory folder.
Copy Using rsync Command
The rsync command in Linux is used to synchronize or transfer data between two locations. Usage is similar to cp , but there are a few key differences to note.
To copy a single file, enter the following into a terminal:
- The –a option means all, and is included with rsync commands – this preserves subdirectories, symbolic links, and other metadata.
- Replace the my_file.txt file in the working directory.
- Replace /new_directory/ with the destination.
- Using my_file_backup.txt as the target indicates the file will be renamed during the copy.
To copy a directory with rsync, enter the following:
This copies the contents of the /etc/docker/ directory to /home/backup/docker/. Make sure to keep the slashes. Omitting the slash on the source directory will copy the contents into a subdirectory.
To omit files from being copied, check out our guide on how to exclude files and directories in data transfer using rsync command.
Other Options
The ls command is a handy partner to the cp command in Linux.
To list the contents of a directory enter the command:
The example above displays all the files in /directory. Use this command after copying to verify the files were copied successfully.
To change directories, use cd and the name of the directory. For example:
The command prompt will change to display that you’ve changed directories.
Now you understand how to copy files in Linux. The cp command is a versatile and powerful tool for managing and backing up files.
Источник