Linux copy with replace

Копирование файлов в 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.

Читайте также:  Windows 10 80004005 сетевая папка

Копирование файлов по регулярным выражениям в Linux

В утилите find можно применять различные условия и регулярные выражения для поиска файлов. Я уже немного писал о ней в статье как найти новые файлы в Linux. Мы можем скопировать все найденные с помощью find файлы, вызвав для каждого из них команду cp. Например, копируем все файлы в текущей директории, содержащие в имени только цифры:

find . -name 5 -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 replace all the contents from one folder with another one

I have folders old and new .

I want to replace all the contents in old/* to new/* . There can be many subdirectories in those folders.

But there can be few files which are not in new/* but are in old/* , so I want them to stay as they are.

How can I do that from a Linux shell?

3 Answers 3

rsync would probably be a better option here. It’s as simple as rsync -a subdir/ ./. check this unix.stackexchage answer for better solutions

use -f with the cp command

suppress cp to overwrite» prompt..

To override cp’s alias you can simply enclose it in quotes:

for more information follow these links:

Use rsync . It will synchronize the directories in one direction. So, if you want to update your old folder with everything from new , but keep what’s in there, just use:

This will, in a first instance, just output the list of files that would be transferred. In that case: Everything found in new will be copied to old , unless it’s already there. Everything in old stays as it is.

If it looks fine to you, remove the —dry-run argument to transmit them for real.

The -avh flags just enable archive mode (which will preserve timestamps, etc.), verbosity and human-readable file-sizes. Nothing will be deleted from the destination unless you specify the —delete flag. Consult man rsync for more information.

Читайте также:  Сертифицированная операционная система linux

Источник

How to force ‘cp’ to overwrite directory instead of creating another one inside?

I’m trying to write a Bash script that will overwrite an existing directory. I have a directory foo/ and I am trying to overwrite bar/ with it. But when I do this:

a new bar/foo/ directory is created. I don’t want that. There are two files in foo/ ; a and b . There are files with same names in bar/ as well. I want the foo/a and foo/b to replace bar/a and bar/b .

9 Answers 9

You can do this using -T option in cp .
See Man page for cp .

So as per your example, following is the file structure.

You can see the clear difference when you use -v for Verbose.
When you use just -R option.

When you use the option -T it overwrites the contents, treating the destination like a normal file and not directory.

This should solve your problem.

If you want to ensure bar/ ends up identical to foo/ , use rsync instead:

If just a few things have changed, this will execute much faster than removing and re-copying the whole directory.

  • -a is ‘archive mode’, which copies faithfully files in foo/ to bar/
  • —delete removes extra files not in foo/ from bar/ as well, ensuring bar/ ends up identical
  • If you want to see what it’s doing, add -vh for verbose and human-readable
  • Note: the slash after foo is required, otherwise rsync will copy foo/ to bar/foo/ rather than overwriting bar/ itself.
    • (Slashes after directories in rsync are confusing; if you’re interested, here’s the scoop. They tell rsync to refer to the contents of the directory, rather than the directory itself. So to overwrite from the contents of foo/ onto the contents of bar/ , we use a slash on both. It’s confusing because it won’t work as expected with a slash on neither, though; rsync sneakily always interprets the destination path as though it has a slash, even though it honors an absence of a slash on the source path. So we need a slash on the source path to make it match the auto-added slash on the destination path, if we want to copy the contents of foo/ into bar/ , rather than the directory foo/ itself landing into bar/ as bar/foo .)

rsync is very powerful and useful, if you’re curious look around for what else it can do (such as copying over ssh).

Источник

Copy and overwrite a file in shell script

I want to copy a certain file to a location, irrespective of that file already exists in the destination or not. I’m trying to copy through shell script.But the file is not getting copied. I’m using the following command

/bin/cp -rf /source/file /destination

but that doesn’t work.

4 Answers 4

this should probably solve the problem.

Your problem might be caused by an alias for cp command created in your system by default (you can see al your aliases by typing «alias»). For example, my system has the following alis by default: alias cp=’cp -i’, where -i overrides -f option, i.e. cp will always prompt for overwriting confirmation.

What you need in such case (that’ll actually work even if you don’t have an alias) is to feed «yes» to that confirmation. To do that simply modify your cp command to look like this:

yes | cp /source/file /destination

This question has been already discussed, however you can write a little script like this:

Explaining this script a little bit

#!/bin/bash : tells your computer to use the bash interpreter.

if [ ! -d «$2» ]; then : If the second variable you supplied does not already exist.

mkdir -p «$2» : make that directory, including any parent directories supplied in the path.

Running mkdir -p one/two/three will make:

If you don’t supply the -p tag then you’ll get an error if directories one and two don’t exist:

fi : Closes the if statement.

cp -R «$1» «$2» : copies files from the first variable you supplied to the directory of the second variable you supplied.

So if you ran script.sh mars pluto , mars would be the first variable ( $1 ) and pluto would be the second variable ( $2 ).

Читайте также:  Затемненный экран windows 10

The -R flag means it does this recursively, so the cp command will go through all the files and folders from your first variable, and copy them to the directory of your second variable.

Источник

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:

  1. Modification time/date
  2. Access time
  3. File flags
  4. File mode
  5. User ID (UID)
  6. Group ID (GID)
  7. Access Control Lists (ACLs)
  8. 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

Источник

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