How can I copy a file to a new location, creating the directory as well

I want to cp a file to another directory but that directory doesn't exist yet.

So I would do:

mkdir /new_place
cp the_file /new_place

Can I do this in one?
I imagine something like cp the_file -m /new_place if "m" stood for "make dir's that don't exist"

Would this be a chance to use scp, rsync or another copying utility?

4 Answers

With --parents you can recreate the directories from the source to the destination. For example:

cp --parents ~/Downloads/test.txt ~/Desktop/

Will create the subdirectories ~/Desktop/home/desgua/Downloads and then copy test.txt into it; and

cp --parents Downloads/test.txt ~/Desktop/

will create ~/Desktop/Downloads.

You can do this with the following command

# rsync --recursive the_file /path/to/your/dir/that/doesn't/exists/

Note: Use of "/" at the end of path:

  • When using "/" at the end of source, rsync will copy the content of the last folder. When not using "/" at the end of source, rsync will copy the last folder and the content of the folder.

  • When using "/" at the end of destination, rsync will paste the data inside the last folder. When not using "/" at the end of destination, rsync will create a folder with the last destination folder name and paste the data inside that folder.

1

desgua's answer is proper and simple way, but what if you need a protable way ? POSIX defines cp without --parent flag, so it's not gonna work across all systems.

One option is to write it in Python if it's installed on the system:

#!/usr/bin/env python3
from os import makedirs
from os.path import exists,basename
from shutil import copyfile
from sys import argv
if len(argv) < 3: print('Not enough args',file=stderr) exit(1)
filename = basename(argv[2])
dirs = argv[2].replace(filename,'')
makedirs(dirs)
copyfile(argv[1],argv[2])

This works as so:

$ ./mkdircp.py /etc/passwd $HOME/foodir/bardir/passwd.copy
$ stat --printf "%F\n" $HOME/foodir/bardir/passwd.copy
regular file
$ head -n 1 $HOME/foodir/bardir/passwd.copy
root:x:0:0:root:/root:/bin/bash

You can easily type two commands by using ;. For instance:

mkdir folder; cp file.html folder

and it should work.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like