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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With