- Ubuntu Copy File Command
- Examples: Copy file1.txt to /tmp directory
- Ubuntu make a backup of each existing destination file
- Copy files interactively
- Copy all files in a directory to another directory by using the star wildcard
- Dealing with permission denied error
- Tip: Searching for commands without knowing their exact names
- 🎯 Как копировать (и вставлять) файлы и каталоги из командной строки Linux
- Скопировать один файл
- Скопируйте папку и ее содержимое
- Копировать несколько файлов
- Копировать все файлы одного типа
- Переместить файл или папку
- Команда cp: правильное копирование папок с файлами в *nix
- Выводы
- Послесловие
Ubuntu Copy File Command
I ‘m a new Ubuntu Linux user. This seems like a newbie question, but I can not seem to find examples to copy files on Ubuntu. How do I copy file to another directory on Ubuntu Linux using command line terminal application? How can I copy files via terminal on Ubuntu Linux desktop?
You need to use cp command to copy file to another directory or external usb disk. The command line syntax is as follows to copy files via terminal:[donotprint]
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | None |
Est. reading time | 10m |
[/donotprint]
cp old_name new_name
cp [options] old_name new_name
cp /path/to/source /path/to/dest/directory/
Examples: Copy file1.txt to /tmp directory
Open the Terminal and type the following command in the current directory to copy a file called file1.txt with the same name into /tmp/ directory:
Use ls command to verify new files:
You can copy multiple files into another directory. In this example, copy the files called foo.txt, bar.doc, resume.pdf into a directory called /media/backup/
Cp command can explain what is being done with -v option:
Sample session from all cp commands featured in this tutorials:
Animated gif: Ubuntu Linux copy files via terminal using cp command demo
Ubuntu make a backup of each existing destination file
In this example, copy file named birthday_party.avi to /media/usbpen/ and make a backup of each existing destination file:
/Documents/ folder to /media/usbpen/
Pass the -r (recursive) option to cp command. In this example, make a copy of an existing directory called
/Documents/, inclusive of all it contents (i.e., files, subdirectories, their subdirectories, etc.), to directory called /media/usbpen/:
Copy files interactively
Pass the -i optipn to cp command to prompts the user to the screen before copying a file that would overwrite an existing file:
- 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 ➔
If you do not wish to overwrite an existing file i.e. overrides a previous -i option, try:
Copy all files in a directory to another directory by using the star wildcard
To copy all files from
/Pictures/ to /nfs/backups/pics/ directory, enter:
In this example, copy all of the files in the current directory that have the filename extension .py into another existing directory called /nfs/backups/python/:
Dealing with permission denied error
If you try to copy files to /root/ or any other system areas, you will see an error that read as follows:
Tip: Searching for commands without knowing their exact names
You can use apropos command to displays a list of all topics in the built-in user manual that are related to the subject. The syntax is:
In this example, get the list of editing programs/commands that are available on a system:
Finally, use whatis and man command to obtain information about the mcedit or vi command that apropos provides:
And there you have it, cp command that copies files and directories on Ubuntu based systems. I strongly suggest that your read cp command man page or see our cp command examples page for more information.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
No offense, but this is so noobish information. It is like posting instructions on how to walk. Only post advanced stuff, or I am going to remove your rss from my daily reads.
It was rather helpful to some of us with less knowledge of Linux terminal than yourself sir.
nixCraft
Linux and Unix tutorials for NEW and seasoned sysadmin.
I think noobie questions are OK. Everyone has to start somewhere and even experienced users can have surprising gaps in their knowledge – probably not many who don’t know cp inside out though 🙂
Anyway imo a better answer to such a noob question might be to describe the command `apropos`, and show a small section of a sample output:
$ apropos copy
Clone (3pm) – recursively copy Perl datatypes
asn1_copy_node (3) – API function
bcopy (3) – copy byte sequence
copysign (3) – copy sign of a number
copysignf (3) – copy sign of a number
copysignl (3) – copy sign of a number
cow-shell (1) – Start a copy-on-write session and invoke a shell.
cp (1) – copy files and directories
cpgr (8) – copy with locking the given file to the password or group file
cpio (1) – copy files to and from archives
cppw (8) – copy with locking the given file to the password or group file
apropos is a great discovery tool for people new to a unix-like OS or new to the command line and is also useful for experienced users. It doesn’t get mentioned very often but in conjunction with man and info pages and a little curiosity it is a great tool for exploring what your system contains and can offer you.
Excellent suggestion. The faq has been updated to include your tip. I appreciate your feedback and post.
@julian67: Yup, give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime.
@Sri: Please unsubscribe. You are not adding anything to the discussion by behaving like this.
…and if you’re really sharp you can then direct him to a fishing tackle retailer and take commission on the sales 🙂
How did you create the animated gif?
good info., the -r was a lifesaver for me.
Thanks for the introductory information. I need a little more.
Regarding, “to copy file to another directory or external usb disk”
It is copying to the USB disk that is opaque to me. I can understand how to copy a file from a terminal prompt it is learning the name of the USB disk that I cannot overcome.
I cannot figure out what the “new_name” would be for the USB disk.
From the Ubuntu GUI file manager I can try to drag and drop but get an error which when expanded says permission denied. So I need a way to give the GUI file manager “sudo” and my PW but see no way to do so.
While I was not able to overcome my problem with the GUI drag and drop. I copied from the terminal. First to find the USB drive navigate to /media and then do ls.
The result was a long or very long human unfriendly string which even with paper and pen I doubt I could write and then type with out several tries. Lets prentend the first few letters of which were “foo….”
But I typed “sudo cp source_file /media.foo” and pressed the tab key to auto fill.
Then press enter and gave it my PW and success.
It was figuring out that a USB disk is “media” and not a “dev” that I had to overcome.
Would still love to know how to do this with the GUI file manager.
Thanks for information
I am wondering if there is a command to make a backup of my software.
On Linux or unixs systems
I have MRI scanner and I want make backup software on mod disk
How can I copy a file to “here”
cp source here
I am currently in my destination directory
Источник
🎯 Как копировать (и вставлять) файлы и каталоги из командной строки Linux
Копирование и вставка файлов – это одна из самых простых вещей, которые вы можете делать на компьютере.
В Linux у вас есть несколько вариантов выполнения этой работы.
В командной строке все более просто, что дает вам больше контроля, а в некоторых случаях значительно упрощает.
Скопировать один файл
Каждый раз, когда вы хотите скопировать файл или папку в командной строке Linux, вы будете использовать команду cp.
cp является сокращением copy.
Синтаксис тоже прост.
Используйте cp, затем файл, который вы хотите скопировать, и место назначения, куда вы хотите его переместить.
Скопируйте папку и ее содержимое
Чтобы скопировать папку и ее содержимое, вам нужно указать команде cp рекурсивное копирование.
Это достаточно просто => с флагом -r.
Весь остальной ваш синтаксис точно такой же.
Флаг -r служит для указания cp, что он работает с каталогом и должен копировать его содержимое.
Копировать несколько файлов
Вы также можете скопировать несколько файлов. Командная строка Linux позволяет указывать сразу несколько элементов в квадратных скобках <>.
Вы можете использовать их, чтобы перечислить имена каждого копируемого файла через запятую.
Все три файла разных типов будут скопированы в каталог Documents.
Копировать все файлы одного типа
Если у вас есть тонна файлов одного типа для копирования, вы можете использовать подстановочный знак *.
Звездочка / подстановочный знак указывает командной строке Linux принимать абсолютно все файлы в этом месте.
Таким образом, если вы скажете Linux, чтобы он копировал * .jpg, он скопирует все файлы JPG, независимо от имени или того, что находится перед частью названия файла .jpg.
Если вы хотите использовать несколько типов файлов, например JPG и PNG, вы можете использовать скобки
Переместить файл или папку
Если вы пришли сюда, чтобы переместить файл из одного места в другое, не создавая дубликаты, это тоже можно сделать легко, но для перемещения файла требуется команда mv.
Источник
Команда 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 имеет значение. Если перепутать, то получите полную белиберду: направление копирования поменяется.
Благодарности:
Источник