Linux CP command that creates new directories as needed

I am making note of this here as I had to tweak what I had found after a fairly long Google search.

This is a custom shell script function I added to my .bashrc to provide the copying of files with the ability to create new directories as needed.
I needed to merge several websites and copy image assets from one site into the other website.

function cpmkdir()
 {
 if [[ -z "$1" || -z "$2" ]]; then
 echo "Usage: cpmkdir SOURCE... DIRECTORY"
 return 1;
 fi
 mkdir -p $(dirname "$2")
 cp -ur "$1" "$2"
 }

This will try to create a directory based on the directory tree you are putting your file.
It will then copy that file in, not replacing it if it’s already there & newer.

Based on: http://www.linuxquestions.org/questions/linux-software-2/cp-create-any-directories-necessary-to-open-the-destination-path-920501/#post4568625.

Leave a Reply