Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have the cp command create any necessary folders for copying a file to a destination [duplicate]

Tags:

linux

bash

cp

When copying a file using cp to a folder that may or may not exist, how do I get cp to create the folder if necessary? Here is what I have tried:

[root@file nutch-0.9]# cp -f urls-resume /nosuchdirectory/hi.txt cp: cannot create regular file `/nosuchdirectory/hi.txt': No such file or directory 
like image 246
omg Avatar asked Jun 04 '09 00:06

omg


People also ask

Does cp command create destination directory?

File copying is a common file operation when we work with the Linux command-line. Usually, we'll use the cp command to copy files. However, the cp command won't work if the target directory doesn't exist.

Can cp command copy directories?

With cp command, you can copy a directory and an entire subdirectory with its content and everything beneath it. cp and rsync are one of the most popular commands for copying files and directory.

How do I create a cp folder?

Copying Directories with cp Command To copy a directory, including all its files and subdirectories, use the -R or -r option. The command above creates the destination directory and recursively copy all files and subdirectories from the source to the destination directory.


2 Answers

To expand upon Christian's answer, the only reliable way to do this would be to combine mkdir and cp:

mkdir -p /foo/bar && cp myfile "$_" 

As an aside, when you only need to create a single directory in an existing hierarchy, rsync can do it in one operation. I'm quite a fan of rsync as a much more versatile cp replacement, in fact:

rsync -a myfile /foo/bar/ # works if /foo exists but /foo/bar doesn't.  bar is created. 
like image 54
lhunath Avatar answered Sep 28 '22 06:09

lhunath


I didn't know you could do that with cp.

You can do it with mkdir ..

mkdir -p /var/path/to/your/dir 

EDIT See lhunath's answer for incorporating cp.

like image 31
Christian Avatar answered Sep 28 '22 06:09

Christian