15412s
15412s

Reputation: 3748

How can I copy files and create path destination folders if they dont exist?

I am trying to copy a folder from source to destination. The destination folder does not always exist.

Which copy command creates the destination folder if it doesn't exist?

Example:

$(CP) $(HOME)/text.txt $(DEST)/dir1/dir2/text.txt

Folders dir1 and dir2 don't always exist and should be created.

Upvotes: 0

Views: 1431

Answers (2)

Idelic
Idelic

Reputation: 15582

If you're using a recent version of GNU make, there's a neat trick you can use to create the directory for any target more or less automatically:

.SECONDEXPANSION:
%/.:
        mkdir -p -- "$*"

Now, for each target where you want the destination directory created, you add "| $$(@D)/." as prerequisite:

$(TARGET) : $(PREREQUISITES) | $$(@D)/.
        ...

Upvotes: 0

Jackson Flint-Gonzales
Jackson Flint-Gonzales

Reputation: 482

What shell are you using?

Regardless, it appears there's no cool shortcut. The best way to go is to simply combine mkdir and cp. Following your example:

mkdir -p dir1/dir2 && cp ~/text.txt ~/dir1/dir2

This command would put test.txt in dir2. Hope this helps!

BTW, the syntax for cp is cp [source] [destination dir]

Upvotes: 1

Related Questions