Linux bash copy directory

How to copy in bash all directory and files recursive?

SourceDir contains also sub-folders. Problem that in DestFolder not only all tree, but in up level all another levels and files. How to fix ?

4 Answers 4

cp -r ./SourceFolder ./DestFolder 

So, to clarify, capital -R option will copy the root dir again; small -r option keeps the root paths the same.

cp is not a bash command but a separate executable, so it is system-specific. True bash commands on the other hand are the same across operating systems.

I had to add a slash at the end of my source folder. Not sure why. I was using build vars too. cp -r «$CONFIG_PATH/» «$CODESIGNING_FOLDER_PATH»

cp -r ./SourceFolder ./DestFolder 

code for a copy with success result

cp -rv ./SourceFolder ./DestFolder 

code for Forcefully if source contains any readonly file it will also copy

cp -rf ./SourceFolder ./DestFolder 

also try this cp -r ./dist/* ./out ;

this command will copy dist/* files to out dir;

@SherylHohman It’s different because he put a /* on the end of the source folder. I don’t know why that matters though.

this response instead of copying the entire folder copies content of the source folder into the destination (./out) folder

You might find it handy to keep your attributes set

cp -arf ./SourceFolder ./DestFolder

cp -arf . throws the error «cp: the -R and -r options may not be specified together.» Changing it to cp -af . solves it. I’m not sure if it’s a typo on your end of if cp -arf . actually worked for you, but I hope this helps in case anyone is getting the same error. Reference: stackoverflow.com/a/32695418/5810737

Источник

Копирование файлов и директорий: команда cp в Linux и MacOS

Перевод статьи «Copy a Directory in Linux – How to cp a Folder in the Command Line in Linux and Unix (MacOS)».

Для копирования файлов или директорий (папок) в Unix-подобных операционных системах (Linux и MacOS) используется команда cp .

Команда cp относительно простая, но ее поведение может изменяться в зависимости от передаваемых опций и того, что именно (файлы или директории) и куда копируется.

Для просмотра документации или руководства по использованию команды cp выполните в терминале команду man cp :

$ man cp NAME cp -- copy files SYNOPSIS cp [OPTIONS] source_file target_file cp [OPTIONS] source_file . target_directory .

Примечание редакции Techrocks. Также для получения справки можно воспользоваться командой cp —help .

Читайте также:  Busybox при загрузке linux

В своей базовой форме эта команда принимает в качестве инпута источник, который вы хотите скопировать, и «пункт назначения» — то, куда именно вы хотите его скопировать. Источником может быть файл, несколько файлов или вообще директория.

cp [OPTIONS] source_file target_file

Как создать копию файла в текущей директории

Чтобы создать копию файла в той же директории, нужно передать команде cp имя исходного файла и имя, которое нужно дать файлу-копии.

Допустим, у вас есть файл a.txt и вы хотите создать его копию под именем b.txt в той же директории:

$ ls a.txt $ cp a.txt b.txt $ ls a.txt b.txt

Для справки: команда ls выводит список файлов в текущей директории.

По умолчанию команда cp использует в качестве пути к файлам вашу текущую директорию.

Как скопировать файл в другую директорию

Чтобы скопировать файл в директорию, отличную от вашей текущей, нужно просто указать путь к ней:

$ ls ../directory-1/ $ cp a.txt ../directory-1/ $ ls ../directory-1/ a.txt

После выполнения команды cp ранее пустая directory-1 содержит файл a.txt.

Примечание редакции Techrocks. В примере показан относительный путь к директории. Две точки перед слэшем означают «родительская директория». Допустим, ваша текущая директория — directory-2, которая находится в директории parent_directory. Команда ls ../directory-1/ выведет список файлов в directory-1, которая тоже находится в parent_directory.

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

$ cp a.txt ../directory-1/b.txt $ ls ../directory-1/ b.txt

Как скопировать несколько файлов в другую директорию

Чтобы одновременно скопировать несколько файлов, вы можете передать команде несколько источников, а в конце указать пункт назначения:

$ ls ../directory-1/ $ cp first.txt second.txt ../directory-1/ $ ls ../directory-1/ first.txt second.txt

В этом примере оба файла (first.txt и second.txt) были скопированы в директорию directory-1.

Примечание: при передаче нескольких источников последний аргумент обязательно должен быть директорией.

Как скопировать одну директорию в другую

Если вы попытаетесь передать команде cp в качестве источника имя директории, вы получите ошибку:

$ cp directory-1 directory-2 cp: directory-1 is a directory (not copied).

Для копирования директории целиком нужно добавить флаг -r (или -R , или —recursive ), указывающий, что копировать надо рекурсивно:

В следующем примере у нас есть две директории (directory-1 и directory-2), расположенные в нашей текущей директории. В directory-1 есть файл a.txt. Мы рекурсивно копируем directory-1 в directory-2. После этого в нашей текущей директории по-прежнему есть directory-1 и directory-2, при этом в directory-2 есть копия directory-1, содержащая файл a.txt.

$ ls directory-1 directory-2 $ ls directory-1 a.txt $ ls directory-2 $ cp -r directory-1 directory-2 $ ls directory-2 directory-1 $ ls directory-2/directory-1 a.txt

Копирование директории целиком и копирование всего содержимого из директории

Примечание редакции Techrocks. Когда мы попробовали применить эту инструкцию в терминале Linux, у нас ничего не вышло. В одной статье мы нашли, что описанный функционал работает в MacOS, но не в Linux. Поэтому здесь мы сначала приведем перевод инструкций автора, а затем от себя дополним их.

Читайте также:  Ubuntu tweak tool linux mint

При копировании директории есть интересный нюанс. Если директория, которую вы указываете как пункт назначения, уже существует, вы можете скопировать в нее либо все содержимое директории-источника, либо всю директорию-источник целиком. Выбор регулируется добавлением конечного слэша / к имени директории-источника.

Вот описание опции -R в мануале ( man ):

Если файл_источник является директорией, cp копирует директорию и все поддерево, подключенное к этой точке. Если файл_источник заканчивается на / , копируется содержимое этой директории, а не сама директория.

Поэтому, если вы хотите скопировать в другое место только файлы и папки из директории-источника, добавьте в конце слэш / .

$ ls directory-1 a.txt $ cp -r directory-1/ directory-2 $ ls directory-1 directory-2 $ ls directory-2 a.txt

Если вы хотите скопировать всю папку вместе со всем ее содержимым, не добавляйте в конце слэш / .

Для пользователей Linux: после слэша нужно добавить точку. Если хотите почитать более подробно, вот хорошая статья на Хабре.

$ ls directory-1 a.txt $ cp -r directory-1/. directory-2 $ ls directory-1 directory-2 $ ls directory-2 a.txt

Как предотвратить перезапись файлов при копировании

По умолчанию команда cp перезаписывает существующие файлы. Для примера создадим в текущей директории файл a.txt с текстом A, а в директории directory-1 — файл a.txt с текстом B. При копировании файла a.txt из текущей директории в directory-1 файл a.txt перезаписывается (в его содержимом было B, стало A).

$ cat a.txt A $ cat directory-1/a.txt B $ cp a.txt directory-1/a.txt $ cat directory-1/a.txt A

Примечание: команда cat среди прочего служит для вывода содержимого файлов на экран.

Есть два способа предотвратить перезапись файлов.

Флаг —interactive

Чтобы при возможной перезаписи получить предупреждение, можно добавить к команде cp флаг -i (или —interactive):

$ cp -i a.txt directory-1/a.txt overwrite directory-1/a.txt? (y/n [n])

Флаг —no-clobber

Флаг -n (или —no-clobber ) позволяет предотвращать перезапись по умолчанию, не спрашивая пользователя:

$ cat a.txt A $ cat directory-1/a.txt B $ cp -n a.txt directory-1/a.txt $ cat directory-1/a.txt B

На этом примере видно, что благодаря флагу -n содержимое файла directory-1/a.txt не было перезаписано.

Другие опции

Команде cp можно передавать много других полезных опций. Например, -v для «многословного» вывода или -f для «принудительного» выполнения. Я советую почитать страницу man , чтобы хотя бы знать, какие есть варианты.

Источник

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.

Читайте также:  Linux command about version

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.

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).

Источник

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