Linux copy folders to another folder

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.

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
Читайте также:  Iso master for linux

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.

Источник

How do I create a copy of a directory in Unix/Linux? [closed]

I want to recursively create a copy of a directory and all its contents (e.g. files and subdirectories).

3 Answers 3

The option you’re looking for is -R .

cp -R path_to_source path_to_destination/ 
  • If destination doesn’t exist, it will be created.
  • -R means copy directories recursively . You can also use -r since it’s case-insensitive.
  • To copy everything inside the source folder (symlinks, hidden files) without copying the source folder itself use -a flag along with trailing /. in the source (as per @muni764 ‘s / @Anton Krug ‘s comment):
cp -a path_to_source/. path_to_destination/ 

i wonder why this exact command in dockerfile copies all source directory files into destination, instead of copying just whole directory.

I believe the ‘/’ on the end makes a difference and that might account for your experience. If the source includes the trailing slash it will copy what is in the directory only. If it does not include the trailing slash, it will copy the directory as well and then the contents inside of it. My memory is this behavior varies by command and maybe event by OS a bit. Here’s a reference with more info.

Читайте также:  Openvpn server gui linux

I would say if you don’t want to include the source and you want to make sure everything is copied (symlinks, hidden files) without copying the source parent folder is to use -ra source/. destination. This will make sure the content of the folder is copied, but not the parent folder itself, which is sometimes handy. And the difference is the /.

Note the importance of «Slash dot» on your source in cp -r src/. dest I know it is mentioned but I still seem to miss it every time.

You are looking for the cp command. You need to change directories so that you are outside of the directory you are trying to copy.

If the directory you’re copying is called dir1 and you want to copy it to your /home/Pictures folder:

Linux is case-sensitive and also needs the / after each directory to know that it isn’t a file. ~ is a special character in the terminal that automatically evaluates to the current user’s home directory. If you need to know what directory you are in, use the command pwd .

When you don’t know how to use a Linux command, there is a manual page that you can refer to by typing:

Also, to auto complete long file paths when typing in the terminal, you can hit Tab after you’ve started typing the path and you will either be presented with choices, or it will insert the remaining part of the path.

There is an important distinction between Linux and Unix in the answer because for Linux (GNU and BusyBox) -R , -r , and —recursive are all equivalent, as mentioned in this answer. For portability, i.e. POSIX compliance, you would want to use -R because of some implementation-dependent differences with -r . It’s important to read the man pages to know any idiosyncrasies that may arise (this is a good use case to show why POSIX standards are useful).

Источник

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

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

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

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

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

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

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

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

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

Читайте также:  Время в linux формате

Чтобы это изменение поведения сохранилось после перезагрузки, можно сделать файл 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. Картинка очень большая и детальная, можно открыть в отдельном окне.

Источник

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