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

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

 

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
[root@file nutch-0.9]# 

besides,any way to make ">" work that way,say to create a directory when need?

[root@file nutch-0.9]# echo test >/nosuchtest/hi.txt
-bash:/nosuchtest/hi.txt:No such file or directory

--parents' Form the name of each destination file by appending to the target directory a slash and the specified name of the source file. The last argument given tocp' must be the name of an existing directory. For example, the command:

      cp --parents a/b/c existing_dir

 copies the file `a/b/c' to `existing_dir/a/b/c', creating any
 missing intermediate directories.
/tmp $ mkdir foo
/tmp $ mkdir foo/foo
/tmp $ touch foo/foo/foo.txt
/tmp $ mkdir bar
/tmp $ cp --parents foo/foo/foo.txt bar
/tmp $ ls bar/foo/foo
foo.txt



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

 

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

 
posted @ 2014-04-22 15:27  alxe_yu  阅读(295)  评论(0)    收藏  举报