- 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
- Copy a Directory in Linux – How to cp a Folder in the Command Line in Linux and Unix (MacOS)
- How to copy a file to the current directory
- How to copy a file to another directory
- How to copy multiple files to a directory
- How to copy a directory to another directory
- How to copy the entire directory vs the contents of the directory
- How to prevent overwriting files with cp
- The interactive flag
- The no-clobber flag
- Other options
- Копирование файлов в Linux
- Утилита копирования файлов cp
- Синтаксис и опции
- Примеры копирования файлов в linux
- Копирование файлов по регулярным выражениям в Linux
- Копирование содержимого файлов в Linux
- Специальное копирование файлов в Linux с помощью tar
- Выводы
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.
Источник
Copy a Directory in Linux – How to cp a Folder in the Command Line in Linux and Unix (MacOS)
To copy files or directories in Unix-based operating systems (Linux and MacOS), you use the cp command.
The cp command is a relatively simple command, but its behavior changes slightly depending on the inputs (files vs directories) and the options you pass to it.
To view the documentation or manual for the cp command, run man cp at your terminal:
The basic form of this command takes an input source (or sources) that you want to copy (files or directories) and a destination to copy the files or directories to:
How to copy a file to the current directory
To copy a file, pass the file you want to copy and the path of where you want to copy the file to.
If you have a file named a.txt , and you want a copy of that file named b.txt :
If you’re not familiar with the ls command, ls «lists» all the contents of a directory.
By default the cp command uses your current directory as the path.
How to copy a file to another directory
To copy a file to a directory that is different from your current directory, you just need to pass the path of the other directory as the destination:
After the cp command, the previously empty directory-1 now contains the file a.txt .
By default the copied file receives the name of the original file, but you can also optionally pass a file name as well:
How to copy multiple files to a directory
To copy more than one file at a time you can pass multiple input sources and a directory as destination:
Here the two input sources ( first.txt and second.txt ) were both copied to the directory directory-1 .
Note: when passing multiple sources the last argument must be a directory.
How to copy a directory to another directory
If you try to pass a directory as the input source, you get this error:
To copy a directory, you need to add the -r (or -R ) flag—which is shorthand for —recursive :
Here directory-1 containing the file a.txt is copied to a new directory called directory-2 —which now also contains the file a.txt .
How to copy the entire directory vs the contents of the directory
There is an interesting edge case when you copy a directory: if the destination directory already exists, you can choose whether to copy the contents of the directory or the entire directory by adding or removing a trailing / from your input.
Here’s the description from the -R option of the man page:
If source_file designates a directory, cp copies the directory and the entire subtree connected at that point. If the source_file ends in a /, the contents of the directory are copied rather than the directory itself.
If you want to copy just the contents of the directory into another directory, add a trailing / to your input.
If you want to copy the contents of the directory and the directory folder itself into another directory, don’t add a trailing / :
Here you can see that because directory-2 already exists—and the input source didn’t have a trailing / —both the contents of directory-1 and the directory itself was copied into the destination.
How to prevent overwriting files with cp
By default, the cp command will overwrite existing files:
If you’re not familiar with the cat or «concatenate» command, it prints the contents of a file.
There are two ways to prevent this.
The interactive flag
To be prompted when an overwrite is about to occur, you can add the -i or —interactive flag:
The no-clobber flag
Or, to prevent overwrites without being prompted, you can add the -n or —no-clobber flag:
Here you can see that thanks to the -n flag the contents of directory-1/a.txt were not overwritten.
Other options
There are many other useful options to pass to the cp command: like -v for «verbose» output or -f for «force.»
I highly encourage you to read through the man page for all of the other useful options.
If you liked this tutorial, I also talk about topics like this on Twitter, and write about them on my site.
A simple web developer who likes helping others learn how to program.
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives and help pay for servers, services, and staff.
Источник
Копирование файлов в 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 6 -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 в целом. Как видите, в терминале это выполняется намного быстрее и эффективнее, чем с помощью графического интерфейса, если помнить нужные команды. Если у вас остались вопросы, спрашивайте в комментариях!
Источник