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

50,746

Solution 1

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.

Solution 2

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.

Solution 3

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
Share:
50,746

Related videos on Youtube

Michael Durrant
Author by

Michael Durrant

Updated on September 18, 2022

Comments

  • Michael Durrant
    Michael Durrant over 1 year

    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?

  • mfink
    mfink almost 6 years
    If you want the_file you need to add a / to the end of your new directory path.