Copy directory linux console

how do you copy a directory and its contents to a new location under a new directory name?

I’m new to the Linux command line and am trying to get to grips with the copy command at the moment. Can anyone please tell me if it’s possible to copy a directory with its subdirectories and associated files to a new directory with a new name, e.g. directory_backup ? Thanks for any and all help in advance.

7 Answers 7

You can use cp with the -r (copy recursively) flag and specify the new directory name:

cp -r /path/to/directory /path/to/location/new-name 

In the above command replace the given paths with the real ones.

For example, to copy stuff from my home directory to an existing directory named backup and name the new directory stuff-backup (if this directory already exists, note that stuff will be copied into it, not overwrite it), you run:

cp -r ~/stuff ~/backup/stuff-backup 

~ is a shortcut for your home directory /home/$USER or /home/zanna in my case. You can omit it if the current working directory is your home directory — you can see this from your prompt

zanna@monster:~$ ^--the ~ here is where I am - home! 

You can add the -v (verbose) flag to make cp report each copy being performed:

$ cp -vr stuff backup/stuff-backup 'stuff/thing1' -> 'backup/stuff-backup/thing1' 'stuff/thing2' -> 'backup/stuff-backup/thing2 . 

Sorry Zanna. I’ll put your advice into practice and see how I go. Like the idea of the verbose flag . assume this will also work as a report while other command are being worked.. Cheers.

The command you need is simply cp which stands for «copy».

You can use it for example with one of these syntaxes:

cp SOURCEFILE TARGETFILE cp SOURCEFILE TARGETDIRECTORY 

The first variant allows you to specify a new file name for the target file, while the second variant creates a copy with the same name in the target directory. You must of course substitute the place holders in capital letters with valid paths first.

However, cp by default operates on files only, not on directories. To get it to copy a complete directory with all its content recursively, you must add the -r option:

cp -r SOURCEDIRECTORY TARGETDIRECTORY 

You can learn more about the cp command by typing man cp in your terminal.

Not used to this comment section Byte Commander. keep hitting return to change line but post instead. Very clear outline in your answer . Look forward to sorting out those directories now that I’ve been given good instruction on the correct usage of the available tools. Excellent.

@OwenHines Just that comments strip any linebreak and additional whitespace and having them in the editor doesn’t change anything in the result.

Читайте также:  Linux if equals string

You can use the below command to copy directory from one place to another sub directory.

cp -Rvp /home/edmuntu/data /home/edmuntu/mydata/ 
  • -R = copy directories recursively
  • v = explain what is being done
  • p = It will help your to preserve your permission and ownership with timestamps

Thank you @Rakesh Chauhan.»preserve your permission and ownership with timestamps» . Wow. I need to get to it. Yet another aspect of line commands to be explored. Thank you for your reply.

As an alternative to the generally useful cp command you can use rsync which has the added benefit of replicating the permissions/timestamps of the original directory structure:

note the slash after the source dir.

Had huge issues with rsync. cp -Rvp with a . after the directory to copy is working well for me (the . will copy hidden files/foders). And @HelloUniverse — if you use the p command with cp, it preserves permissions, ownership, timestamps

cp is the command that does the function that you’re looking for. It stands for copy and it does just that. The command that would work for you in this situation is

This would copy the source/ folder and all of its sub-directories to destination/ .

If destination/ doesn’t exist, it will be created.

The -R flag stands for recursive, which tells cp to copy all sub-directories.

@Edmuntu Glad I could help, if you found the solution to your issue, can you please mark the answer that worked for you as the correct one by clicking the check mark under it? This will help alert others who view the page of the question being solved.

I find it easier to change to the directory I’m copying from first. For this example change to a directory everyone has called /boot . Anyone can copy and paste the commands below into their Terminal.

cd /boot sudo mkdir /boot_backup sudo cp -r . /boot_backup du /boot_backup -h 752K /boot_backup/extlinux/themes/debian-wheezy 756K /boot_backup/extlinux/themes 832K /boot_backup/extlinux 2.5M /boot_backup/grub/i386-pc 20K /boot_backup/grub/locale 2.3M /boot_backup/grub/fonts 7.2M /boot_backup/grub 565M /boot_backup 

For the cp command the current directory is identified as . which is the /boot directory we changed to. The -r option makes it recursive to include all sub-directories.

To ensure it worked run du to list all sub-directories and total file sizes in the new directory /boot_backup in this case.

After finishing this walk-through, use: sudo rm -r /boot_backup to remove the new directory and it’s sub-directories.

Источник

Команда cp: правильное копирование папок с файлами в *nix

В этой статье будут раскрыты некоторые неочевидные вещи связанные с использованием wildcards при копировании, неоднозначное поведение команды cp при копировании, а также способы позволяющие корректно копировать огромное количество файлов без пропусков и вылетов.

Допустим нам нужно скопировать всё из папки /source в папку /target.

Первое, что приходит на ум это:

Сразу исправим эту команду на:

Ключ -a добавит копирование всех аттрибутов, прав и добавит рекурсию. Когда не требуется точное воспроизведение прав достаточно ключа -r .

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

.profile
.local
.mc
и тому подобные.

Потому что wildcards обрабатывает shell ( bash в типовом случае). По умолчанию bash проигнорирует все файлы начинающиеся с точек, так как трактует их как скрытые. Чтобы избежать такого поведения нам придётся изменить поведение bash с помощью команды:

Читайте также:  Linux list process listening on port

Чтобы это изменение поведения сохранилось после перезагрузки, можно сделать файл wildcard.sh c этой командой в папке /etc/profile.d (возможно в вашем дистрибутиве иная папка).

А если в директории-источнике нет файлов, то shell не сможет ничего подставить вместо звёздочки, и также копирование завершится с ошибкой. Против подобной ситуации есть опции failglob и nullglob . Нам потребуется выставить failglob , которая не даст команде выполниться. nullglob не подойдёт, так как она строку с wildcards не нашедшими совпадения преобразует в пустую строку (нулевой длины), что для cp вызовет ошибку.

Однако, если в папке тысячи файлов и больше, то от подхода с использованием wildcards стоит отказаться вовсе. Дело в том, что bash разворачивает wildcards в очень длинную командную строку наподобие:

cp -a /souce/a /source/b /source/c …… /target

На длину командной строки есть ограничение, которое мы можем узнать используя команду:

Получим максимальную длину командной строки в байтах:

…. Maximum length of command we could actually use: 2089314 ….

Итак, давайте будем обходиться вовсе без wildcards.

И тут мы столкнёмся с неоднозначностью поведения cp . Если папки /target не существует, то мы получим то, что нам нужно.

Однако, если папка target существует, то файлы будут скопированы в папку /target/source.

Не всегда мы можем удалить заранее папку /target, так как в ней могут быть нужные нам файлы и наша цель, допустим, дополнить файлы в /target файлами из /source.

Если бы папки источника и приёмника назывались одинаково, например, мы копировали бы из /source в /home/source, то можно было бы использовать команду:

И после копирования файлы в /home/source оказались бы дополненными файлами из /source.

Такая вот логическая задачка: мы можем дополнить файлы в директории-приёмнике, если папки называются одинаково, но если они отличаются, то папка-исходник будет помещена внутрь приёмника. Как скопировать файлы из /source в /target с помощью cp без wildcards?

Чтобы обойти это вредное ограничение мы используем неочевидное решение:

Те кто хорошо знаком с DOS и Linux уже всё поняли: внутри каждой папки есть 2 невидимые папки «.» и «..», являющиеся псевдопапками-ссылками на текущую и вышестоящие директории.

  • При копировании cp проверяет существование и пытается создать /target/.
  • Такая директория существует и это есть /target
  • Файлы из /source скопированы в /target корректно.

Поведение этой команды однозначно. Всё отработает без ошибок вне зависимости от того миллион у вас файлов или их нет вовсе.

Выводы

Если нужно скопировать все файлы из одной папки в другую, не используем wildcards, вместо них лучше использовать cp в сочетании с точкой в конце папки-источника. Это скопирует все файлы, включая скрытые и не завалится при миллионах файлов или полном отсутствии файлов.

Послесловие

vmspike предложил аналогичный по результату вариант команды:

ВНИМАНИЕ: регистр буквы T имеет значение. Если перепутать, то получите полную белиберду: направление копирования поменяется.
Благодарности:

  • Компании RUVDS.COM за поддержку и возможность публикации в своем блоге на Хабре.
  • За изображение TripletConcept. Картинка очень большая и детальная, можно открыть в отдельном окне.

Источник

How to Copy a Directory in Linux Command Line [Beginner’s Tip]

This quick tip for beginners demonstrates how to copy a directory in Linux using the cp command. You’ll also learn a few additional tips around copying directory.

Читайте также:  Windows viruses on linux

If you are new to Linux command line, you probably have this question in mind: How do I copy a directory and the files inside it to another directory in Linux command line?

Here’s how to copy a directory in Linux:

cp -r source_directory destination_directory

You probably already know that you can use cp command to copy files in Linux. Do you know that you can use the same cp command to copy a folder in Linux command line?

Hah! You already tried that and perhaps got this error:

cp: -r not specified; omitting directory 'test_dir'

Let me show you a thing or two about copying directory in Linux.

Copy directory in Linux command line

You can definitely use the same cp command but with the recursive option -r to copy a folder with its content to another folder. The above mentioned error also hints that you missed the -r option.

All you got to do is to use the command in this fashion:

cp -r source_directory destination_directory

And now if you use ls command on the destination directory, it should have the entire source directory inside it.

The -r option allows the recursive option. This means the entire content of the directory including its own subdirectories, everything in the directory will be copied to the destination.

A few things to note about copying directory in Linux

Here are a couple of things to note and tips about copying folders.

The destination directory doesn’t exist? It will be created

If the destination directory doesn’t exist (but the path exists), it will be created up to one level (explained in the next section). However, it will now copy the contents of the source directory, not the source directory itself.

For example, if you do this:

cp -r source_directory non_existing_directory

The non_existing_directory will be created with the content of the source_directory but it won’t have the source_directory inside it. Just the files of source_directory will be copied. It would be like non_existing_directory will be a replica of source_directory.

[email protected]:~$ ls test_dir [email protected]:~$ cp -r test_dir new_dir [email protected]:~$ tree . ├── new_dir │ ├── c.xyz │ ├── myzip1.zip │ └── myzip2.zip └── test_dir ├── c.xyz ├── myzip1.zip └── myzip2.zip 2 directories, 6 files

Can’t create nested directory while copying

You cannot use the above command to create nested directory structure.

For example, if you try to use cp -r source_dir dir1/dir2/dir3 but dir2 and dir3 don’t exist, it won’t create the nested directory structure and the command fails.

Preserve the original file attributes

One last tip to keep things short. If you use the -a option along with the -r option, it will preserve the original file information such as file permissions, file timestamps etc. It will archive the directory to the new location instead of creating it afresh.

This much information should be enough for you to know how to copy a directory in Linux. If you have questions or suggestions, please feel free to leave a comment.

Источник

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