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
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.
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.
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.
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.
mkdir -p "$d" && cp file "$d"
(there's no such option for cp
).
If both of the following are true:
cp
(and not, for instance, the Mac version), andthen 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
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