- Команда cp: правильное копирование папок с файлами в *nix
- Выводы
- Послесловие
- Linux – How To Copy a Folder [ Command Line Option ]
- How To Copy a Folder with cp Command
- Linux cp command examples
- More examples of cp command to copy folders on Linux
- Use Linux rsync Command to copy a folder
- Conclusion
- How to Copy a Directory in Linux Command Line [Beginner’s Tip]
- Copy directory in Linux command line
- A few things to note about copying directory in Linux
- The destination directory doesn’t exist? It will be created
- Can’t create nested directory while copying
- Preserve the original file attributes
- How do I copy folder with files to another folder in Unix/Linux? [closed]
- 3 Answers 3
- How To Copy Entire Directory In Linux?
- Copy Only Directory
- Copy Entire Directory Recursively
- Copy Special Files
- Copy While Preserving Source Directory Attributes
- Copy Entire Directory To The Current User Home Directory
- Copy Verbosely Providig Detailed Information
- Copy Entire Directory with rsync Command
Команда cp: правильное копирование папок с файлами в *nix
В этой статье будут раскрыты некоторые неочевидные вещи связанные с использованием wildcards при копировании, неоднозначное поведение команды cp при копировании, а также способы позволяющие корректно копировать огромное количество файлов без пропусков и вылетов.
Допустим нам нужно скопировать всё из папки /source в папку /target.
Первое, что приходит на ум это:
Сразу исправим эту команду на:
Ключ -a добавит копирование всех аттрибутов, прав и добавит рекурсию. Когда не требуется точное воспроизведение прав достаточно ключа -r .
После копирования мы обнаружим, что скопировались не все файлы — были проигнорированы файлы начинающиеся с точки типа:
.profile
.local
.mc
и тому подобные.
Почему же так произошло?
Потому что wildcards обрабатывает shell ( bash в типовом случае). По умолчанию bash проигнорирует все файлы начинающиеся с точек, так как трактует их как скрытые. Чтобы избежать такого поведения нам придётся изменить поведение bash с помощью команды:
Чтобы это изменение поведения сохранилось после перезагрузки, можно сделать файл wildcard.sh c этой командой в папке /etc/profile.d (возможно в вашем дистрибутиве иная папка).
А если в директории-источнике нет файлов, то shell не сможет ничего подставить вместо звёздочки, и также копирование завершится с ошибкой. Против подобной ситуации есть опции failglob и nullglob . Нам потребуется выставить failglob , которая не даст команде выполниться. nullglob не подойдёт, так как она строку с wildcards не нашедшими совпадения преобразует в пустую строку (нулевой длины), что для cp вызовет ошибку.
Однако, если в папке тысячи файлов и больше, то от подхода с использованием wildcards стоит отказаться вовсе. Дело в том, что bash разворачивает wildcards в очень длинную командную строку наподобие:
На длину командной строки есть ограничение, которое мы можем узнать используя команду:
Получим максимальную длину командной строки в байтах:
Получим что-то типа:
Итак, давайте будем обходиться вовсе без 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 имеет значение. Если перепутать, то получите полную белиберду: направление копирования поменяется.
Благодарности:
Источник
Linux – How To Copy a Folder [ Command Line Option ]
How To Copy a Folder with cp Command
The cp command is a Linux command for copying files and directories. The syntax is as follows:
Linux cp command examples
In this example copy /home/vivek/letters/ folder and all its files to /usb/backup/ directory:
cp -avr /home/vivek/letters /usb/backup
Where,
- -a : Preserve the specified attributes such as directory an file mode, ownership, timestamps, if possible additional attributes: context, links, xattr, all.
- -v : Verbose output.
- -r : Copy directories recursively.
More examples of cp command to copy folders on Linux
Copy a folder called /tmp/conf/ to /tmp/backup/:
$ cp -avr /tmp/conf/ /tmp/backup/
Sample outputs:
Fig.01: cp command in action
Use Linux rsync Command to copy a folder
You can also use rsync command which is a fast and extraordinarily versatile file copying tool. It can make copies across the network. The syntax is as follows for the rsync command
To backup my home directory, which consists of large files and mail folders to /media/backup, enter:
$ rsync -avz /home/vivek /media/backup
I can copy a folder to remote machine called server1.cyberciti.biz as follows:
$ rsync -avz /home/vivek/ server1.cyberciti.biz:/home/backups/vivek/
Where,
- 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 ➔
- -a : Archive mode i.e. copy a folder with all its permission and other information including recursive copy.
- -v : Verbose mode.
- -z : With this option, rsync compresses the file data as it is sent to the destination machine, which reduces the amount of data being transmitted something that is useful over a slow connection.
Fig.02: rsync command in action
Conclusion
You just learned how to copy a folder on a Linux like operating system using the cp command and rsync command. In conclusion, use rsync for a network folder transfer and cp for a local disk transfer.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
How to Copy a Directory in Linux Command Line [Beginner’s Tip]
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:
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:
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:
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:
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.
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.
That’s it
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.
Источник
How do I copy folder with files to another folder in Unix/Linux? [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
Closed 8 years ago .
I am having some issues to copy a folder with files in that folder into another folder. Command cp -r doesn’t copy files in the folder.
3 Answers 3
The option you’re looking for is -R .
- 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):
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:
at a terminal prompt.
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.
Источник
How To Copy Entire Directory In Linux?
Linux provides different tools to copy directories entirely. The most popular and well-known tool is cp . In this tutorial, we will look at how to copy Linux directories entirely or specific content.
Copy Only Directory
In this first example, we will copy the only directory. We can just provide the source directory and destination directory names to the cp command. In this example, we will try to copy a single directory. As we can see we get an error like below.
Copy Entire Directory Recursively
Now here is the real scenario. We will copy our directory named backup with a new named newbackup . We will use the -r option which makes copy operation recursively. Recursive means subdirectories and files will be copied too.
Copy Special Files
During recursive copy operation, special file content will not be copied by default. We can copy special file contents with the -b option like below.
Copy While Preserving Source Directory Attributes
Files and directories provide some attributes in Linux operating systems. These attributes are file mode, ownership, timestamp, context, links, xattr, etc. During directory copy, we can copy these attributes too with the -a option like below.
Copy Entire Directory To The Current User Home Directory
Linux bash shell provides some shortcuts about the paths. If we want to copy a directory completely into the current user home directory we can
tilde to specify the user home directory path. In this example, we will copy the directory named backup to the current user home directory.
Copy Verbosely Providig Detailed Information
During copy operation, there will be no sign about the current operation. We can make this copy operation verbose where copied files will be printed to the shell. We will use -v command like below.
Copy Entire Directory with rsync Command
rsync is very popular and useful tools used to copy, sync, and backup files and directories. We can use rsync in order to copy the complete directory with its subdirectories locally or to the remote systems. We will use -r options to copy all directories and files recursively and also use -v option for verbose output.
Источник