Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux: copy and create destination dir if it does not exist

I want a command (or probably an option to cp) that creates the destination directory if it does not exist.

Example:

cp -? file /path/to/copy/file/to/is/very/deep/there 
like image 770
flybywire Avatar asked Oct 07 '09 06:10

flybywire


People also ask

How do you create a directory if it doesn't exist in Linux?

When you want to create a directory in a path that does not exist then an error message also display to inform the user. If you want to create the directory in any non-exist path or omit the default error message then you have to use '-p' option with 'mkdir' command.

How do you mkdir only if a DIR does not already exist?

You can either use an if statement to check if the directory exists or not. If it does not exits, then create the directory. You can directory use mkdir with -p option to create a directory. It will check if the directory is not available it will.

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.

How do you create a file then copy it to a different directory in Linux?

The Linux cp command is used for copying files and directories to another location. To copy a file, specify “cp” followed by the name of a file to copy. Then, state the location at which the new file should appear. The new file does not need to have the same name as the one you are copying.


2 Answers

mkdir -p "$d" && cp file "$d" 

(there's no such option for cp).

like image 55
Michael Krelin - hacker Avatar answered Oct 23 '22 13:10

Michael Krelin - hacker


If both of the following are true:

  1. You are using the GNU version of cp (and not, for instance, the Mac version), and
  2. You are copying from some existing directory structure and you just need it recreated

then you can do this with the --parents flag of cp. From the info page (viewable at http://www.gnu.org/software/coreutils/manual/html_node/cp-invocation.html#cp-invocation or with info cp or man cp):

--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 to `cp' 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. 

Example:

/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 
like image 37
Paul Whipp Avatar answered Oct 23 '22 15:10

Paul Whipp