0

I would like to copy a file to a folder that does not exist by having cp create the destination folder and placing a source file into it. Is this possible?

So here is an example, I have a file on my desktop called temp.file. I would like to do this:

cp temp.file ./createThisFolder/

I looked through the man pages and didn't see anything. The reason I want to do this is because I want to run a test on the directory later on. If the directory doesn't exist I know there are no files waiting for me.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
nullByteMe
  • 6,141
  • 13
  • 62
  • 99
  • Possible duplicate of [linux: copy and create destination dir if it does not exist](http://stackoverflow.com/questions/1529946/linux-copy-and-create-destination-dir-if-it-does-not-exist) and [How to have the cp command create any necessary folders for copying a file to a destination](http://stackoverflow.com/questions/947954/how-to-have-the-cp-command-create-any-necessary-folders-for-copying-a-file-to-a) – Vilsepi Jun 12 '13 at 15:32
  • Does this answer your question? [Linux: copy and create destination dir if it does not exist](https://stackoverflow.com/questions/1529946/linux-copy-and-create-destination-dir-if-it-does-not-exist) – Pound Hash Feb 07 '22 at 18:22
  • Does this answer your question? [How to have the cp command create any necessary folders for copying a file to a destination](https://stackoverflow.com/questions/947954/how-to-have-the-cp-command-create-any-necessary-folders-for-copying-a-file-to-a) – tripleee Feb 08 '22 at 06:29

1 Answers1

2

before your copy, you need to perform

mkdir -p ./createThisFolder

If you want to know whether or not there are files in the directory, I'd recommend directly checking whether or not your files exist (instead of checking if the directory exists). For instance:

if [ ! -s ./createThisFolder/temp.file ] ; then 
     echo "file doesn't exist (or it is empty)"
fi 
asf107
  • 1,118
  • 7
  • 22