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

571,767

Solution 1

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.

Solution 2

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.

Solution 3

 mkdir -p `dirname /nosuchdirectory/hi.txt` && cp -r urls-resume /nosuchdirectory/hi.txt

Solution 4

One can also use the command find:

find ./ -depth -print | cpio -pvd newdirpathname

Solution 5

There is no such option. What you can do is to run mkdir -p before copying the file

I made a very cool script you can use to copy files in locations that doesn't exist

#!/bin/bash
if [ ! -d "$2" ]; then
    mkdir -p "$2"
fi
cp -R "$1" "$2"

Now just save it, give it permissions and run it using

./cp-improved SOURCE DEST

I put -R option but it's just a draft, I know it can be and you will improve it in many ways. Hope it helps you

Share:
571,767
omg
Author by

omg

Updated on July 08, 2022

Comments

  • omg
    omg almost 2 years

    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